码迷,mamicode.com
首页 > 编程语言 > 详细

python web1(解析url)

时间:2018-10-28 19:31:00      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:def   切片   div   prot   ima   else   教程   int   erro   

环境:pycharm

尝试对地址进行切片 去掉头 http 或 https

a.遇到了一些问题

url = https://www.cnblogs.com/derezzed/articles/8119592.html
    #检查协议
protocl = "http"
if url[:7] =="http://":
    u = url.split(://)[1]
    elif url[:8] == "https://":
    protocl = "https"
    u = url.split("://")
   else:
    u = url
    print(u)

技术分享图片

发现无任何输出 

url = https://www.cnblogs.com/derezzed/articles/8119592.html
    #检查协议
protocl = "http"
if url[:7] =="http://":
    u = url.split(://)[1]
    print(u)
elif url[:8] == "https://":
    protocl = "https"
    u = url.split("://")
    print(u)
else:
    u = url
    print(u)

技术分享图片

 

修改后看到了结果 至于为何 暂不知道原因 

 

b.按着教程 边理解 边写出的解析url程序 (此程序有问题)

#url = ‘http://movie.douban.com/top250‘
#解析url 返回一个tuple 包含 protocol host path port

def parsed_url(url):
#检查协议

protocol = ‘http‘
if url[:7] == ‘http://‘:
a = url.split(‘://‘)[1]

elif url[:8] == ‘https://‘:
a = url.split(‘https://‘)[1]
protocol = ‘https‘


#检查默认path
i = a.find(‘/‘)
if(i == -1):
path = ‘/‘
host = a
else:
host = a[:16]
path = a[6:]

#检查端口
port_dict = {
‘http‘: 80,
‘https‘ : 443,
}
#默认端口
port = port_dict[protocol]
if ‘:‘ in host:
h = host.split(‘:‘)
host = h[0]
port = int (h[1])

return protocol, host, port, path
 

 写完后发现编译器一直报错 对着源程序反复确认还是找不到问题所在 一直报错

 “python illegal target for variable annotation”

最后发现是缩进问题 详情查看我的 python learn 或者搜索python的缩进要求

而后加入测试程序 发现还是不对 虽然报错很明显 但依然不知道错在哪里 冷静下来观察错误

技术分享图片

这里看到 错误已经很明显 给出了来源 自己写的(其实是仿着写的qwq)所以没有意识到自己写的expected函数连正确答案都显示出来了 (汗)

最终 马上意识到 host path是有问题的 将 i 替换成了具体数字 修改后错误消失

技术分享图片

技术分享图片

 

error 0 了 啊太棒了 !!! 加油~~~

 

python web1(解析url)

标签:def   切片   div   prot   ima   else   教程   int   erro   

原文地址:https://www.cnblogs.com/junkdog/p/9839684.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!