1.urlparse
用于解析网络链接,用于实现URL各部分的抽取、合并和装换
#!usr/bin/env python
#-*- coding:utf-8 -*-
from urllib.parse import urlparse
result = urlparse('http://news.baidu.com/?tn=news')
print(result)
result = urlparse(url,scheme=‘ ’,allow_fragments=true)
from urllib.parse import urlparse
result = urlparse('http://news.baidu.com/?tn=news')
print(type(result),result[0],result[1],result[2],result[3],sep='\n')
2.urlunparse
#!usr/bin/env python
#-*- coding:utf-8 -*-
from urllib.parse import urlunparse
data=['http','www.baidu.com','index.html','user','a=6','comment']
print(urlunparse(data))
结果为:http://www.baidu.com/index.html;user?a=6#comment
3.urlsplit()和urlunsplist()
urlsplit和urlsparse类似,区别在params部分 path和参数合在一起
4.urljoin()
>>> urljoin("http://www.google.com/1/aaa.html","bbbb.html")
'http://www.google.com/1/bbbb.html'
>>> urljoin("http://www.google.com/1/aaa.html","2/bbbb.html")
'http://www.google.com/1/2/bbbb.html'
>>> urljoin("http://www.google.com/1/aaa.html","/2/bbbb.html")
'http://www.google.com/2/bbbb.html'
>>> urljoin("http://www.google.com/1/aaa.html","http://www.google.com/3/ccc.html")
'http://www.google.com/3/ccc.html'
>>> urljoin("http://www.google.com/1/aaa.html","http://www.google.com/ccc.html")
'http://www.google.com/ccc.html'
>>> urljoin("http://www.google.com/1/aaa.html","javascript:void(0)")
'javascript:void(0)'
提供一个基础的连接作为第一个参数,将新的连接作为第二个参数。
方法会分析分析第一个参数的scheme、netloc和path这三个内容。对新的内容的缺失的地方进行补充,最后返回结果。
也就是说,如果新的连接存在就使用新的链接的内容,不存在到第一个参数里面去找。
5.urlencode和parse_qs
5.1序列化urlencode
在构造GET请求参数的时候很有用
首先,声明一个字典
然后调用urlencode()方法将其序列化为GET请求
#!usr/bin/env python
#-*- coding:utf-8 -*-
from urllib.parse import urlencode
params={
'name':'huangwei',
'age':'12'
}
url='www.baidu.com'+urlencode(params)
print(url)
结果为:www.baidu.comname=huangwei&age=12
5.2反序列化parse_qs
#!usr/bin/env python
#-*- coding:utf-8 -*-
from urllib.parse import urlencode,parse_qs
params={
'name':'huangwei',
'age':'12'
}
reault = parse_qs(urlencode(params))
print(reault)
结果为:{'name': ['huangwei'], 'age': ['12']}
5.2.1反序列化parse_qsl
反序列化为元祖
#!usr/bin/env python
#-*- coding:utf-8 -*-
from urllib.parse import urlencode,parse_qs
params={
'name':'huangwei',
'age':'12'
}
reault = parse_qsl(urlencode(params))
print(reault)
6.quote和unquote
6.1quote
将内容转化为URL编码格式。防止中文乱码
#!usr/bin/env python
#-*- coding:utf-8 -*-
from urllib.parse import quote
key='笔画'
url = 'www.baidu.com'+quote(key)
print(url)
6.2unquote
#!usr/bin/env python
#-*- coding:utf-8 -*-
from urllib.parse import quote,unquote
key='笔画'
url = 'www.baidu.com'+quote(key)
print(url)
reault = unquote(url)
print(reault)