python web1(解析url)

环境: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的缩进要求

而后加入测试程序

def test_parsed_url():
    """
    parsed_url 函数很容易出错, 所以我们写测试函数来运行看检测是否正确运行
    """
    http = 'http'
    https = 'https'
    host = 'g.cn'
    path = '/'
    test_items = [
        ('http://g.cn', (http, host, 80, path)),
        ('http://g.cn/', (http, host, 80, path)),
        ('http://g.cn:90', (http, host, 90, path)),
        ('http://g.cn:90/', (http, host, 90, path)),
        #
        ('https://g.cn', (https, host, 443, path)),
        ('https://g.cn:233/', (https, host, 233, path)),
    ]
    for t in test_items:
        url, expected = t
        u = parsed_url(url)
        # assert 是一个语句, 名字叫 断言
        # 如果断言成功, 条件成立, 则通过测试, 否则为测试失败, 中断程序报错
        e = "parsed_url ERROR, ({}) ({}) ({})".format(url, u, expected)
        assert u == expected, e

发现还是不对 虽然报错很明显 但依然不知道错在哪里 冷静下来观察错误

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

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

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

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