美文网首页Python爬虫笔记
python爬虫day-9(urllib库-解析链接02)

python爬虫day-9(urllib库-解析链接02)

作者: 南音木 | 来源:发表于2019-04-12 17:34 被阅读0次

    个人学习笔记,方便自己查阅,仅供参考,欢迎交流

    解析链接

    3.urlsplit()

    这个方法和urlparse()方法非常相 似,只不过它不再单独解析params部分,只返回5个结果。

    from urllib.parse import urlsplit
    
    result = urlsplit('http://www.baidu.com/index.html;user?id=5#comment')
    print(result)
    

    运行结果:
    SplitResult(scheme='http', netloc='www.baidu.com', path='/index.html;user', query='id=5', fragment='comment')

    from urllib.parse import urlsplit
    
    result =urlsplit('http://www.baidu.com/index.html;user?id=5#comment')
    print(result.scheme,result[0])
    

    运行结果:
    http http

    4.urlunsplit()

    与urlunparse()类似,它也是将链接各个部分组合成完整链接的方法,传入的参数也是一个可迭代对象,例如列表、元组等。

    from urllib.parse import urlunsplit
    
    data=['http','www.baidu.com','index.html','a=6','comment']
    print(urlunsplit(data))
    

    运行结果:
    http://www.baidu.com/index.html?a=6#comment

    5.urljoin()

    生成链接还有其他方法,那就是urljoin()方法,我们可以提供一个base_url(基础链接)作为第一个参数,将新的链接作为第二个参数,该方法会分析 base_url的scheme、netloc和path这3个内容并对新链接缺失的部分进行补充,最后返回结果。

    from urllib.parse import urljoin
    
    print(urljoin('http://www.baidu.com','index.html'))
    print(urljoin('http://www.baidu.com','http://www.destinystar.cn/index.html'))
    print(urljoin('http://www.baidu.com/index1.html','http://www.destinystar.cn/index.html'))
    print(urljoin('http://www.baidu.com/index1.html','http://www.destinystar.cn/index.html?id=2'))
    print(urljoin('http://www.baidu.com?id=123','http://www.destinystar.cn/index.php'))
    print(urljoin('http://www.baidu.com','?idcard=2#comment'))
    print(urljoin('www.baidu.com','?idcard=2#comment'))
    print(urljoin('www.baidu.com#comment','?idcard=2'))
    

    运行结果:
    http://www.baidu.com/index.html
    http://www.destinystar.cn/index.html
    http://www.destinystar.cn/index.html
    http://www.destinystar.cn/index.html?id=2
    http://www.destinystar.cn/index.php
    http://www.baidu.com?idcard=2#comment
    www.baidu.com?idcard=2#comment
    www.baidu.com?idcard=2

    6.urlencode()
    from urllib.parse import urlencode
    
    params = {
            'name':'germey',
            'age':22
            }
    base_url = 'http://www.baidu.com?'
    url = base_url + urlencode(params)
    print(url)
    

    运行结果:
    http://www.baidu.com?name=germey&age=22

    7.parse_qs()

    有了序列化,必然就有反序列化,如果我们有一串GET请求参数,利用 parse_qs()方法,就可以将它转回字典。

    from urllib.parse import parse_qs
    
    query = 'name=germey&age=22'
    print(parse_qs(query))
    

    运行结果:
    {'name': ['germey'], 'age': ['22']}

    8.parse_qsl()

    parse_qs()方法,它用于将参数转化为元组组成的列表。

    from urllib.parse import parse_qsl
    
    query = 'name=germey&age=22'
    print(parse_qsl(query))
    

    运行结果:
    [('name', 'germey'), ('age', '22')]

    相关文章

      网友评论

        本文标题:python爬虫day-9(urllib库-解析链接02)

        本文链接:https://www.haomeiwen.com/subject/fqvqwqtx.html