使用 urllib 解析 URL 链接
urllib 库还提供了 parse 模块,它定义了处理 URL 的标准接口,例如实现 URL 各部分的抽取、合并以及链接转换,常用的方法如下:
In [1]: from urllib.parse import urlparse, urlunparse, urlsplit, urlunsplit, urljoin, parse_qs, parse_qsl, quote, unquote //urlparse()用于对一个URL进行分段 In [2]: urlparse("http://www.baidu.com/index.html;user?id=5#comment") Out[2]: ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment') //urlunparse()用于构造一个URL In [5]: urlunparse(['http', 'www.baidu.com', '/index.html', 'user', 'id=5', 'comment']) Out[5]: 'http://www.baidu.com/index.html;user?id=5#comment' //urlsplit() 与 urlparse() 用法一致,但只运回5个结果,params 会合并到 path 中 In [7]: urlsplit("http://www.baidu.com/index.html;user?id=5#comment") Out[7]: SplitResult(scheme='http', netloc='www.baidu.com', path='/index.html;user', query='id=5', fragment='comment') //urlunsplit() 与 urlunparse() 用法一致,但传入的长度必须是5个 In [11]: urlunsplit(['http', 'www.baidu.com', '/index.html', 'id=5', 'comment']) Out[11]: 'http://www.baidu.com/index.html?id=5#comment' //urljoin()用于生成链接,第一个参数是基础URL,第二个参数相对URL,连结两个参数生成一个新的链接 In [13]: urljoin('http://www.baidu.com/', 'FAQ.html') Out[13]: 'http://www.baidu.com/FAQ.html' //urlencode()用于序列化GET请求参数,通常用来构造请求链接 In [27]: base_url = "http://www.baidu.com" In [28]: params = {'name': 'Tom', 'age': 18} In [29]: base_url + urlencode(params) Out[29]: 'http://www.baidu.comname=Tom&age=18' //parse_qs()用于反序列化GET请求参数 In [30]: query = "name=Tom&age=18" In [32]: parse_qs(query) Out[32]: {'name': ['Tom'], 'age': ['18']} //parse_qsl()用于将参数转化为元组组成的列表 In [34]: query = "name=Tom&age=18" In [35]: parse_qsl(query) Out[35]: [('name', 'Tom'), ('age', '18')] //quote()用于对URL进行编码,将内容转化为URL编码的格式 In [37]: "http://www.baidu.com/" + quote("你好") Out[37]: 'http://www.baidu.com/%E4%BD%A0%E5%A5%BD' //unquote()用于对URL进行解码 In [41]: unquote("http://www.baidu.com/%E4%BD%A0%E5%A5%BD") Out[41]: 'http://www.baidu.com/你好'