urllib是python内置的http请求库。
url有4个模块,request,error,parse和robotparser。
urllib.request
1.urlopen
urllib.request.urlopen(url, data=None, [timeout,]*)
第一个参数为请求的url,可以是Request对象。
第二个参数为传送的数据
第三个参数为超时时间
返回值为一个对象,可以进行read()、status、getheaders()等操作。
2.Request对象
urllib.request.Request(url, data=None, headers={}, method=None)
第三个参数为请求头
第四个参数为请求方式
3.ProxyHandler对象
urllib.request.ProxyHandler(proxies=None)
参数为代理ip列表,返回一个Handler
4.build_opener
urllib.request.build_opener([handler, ...])
参数为handler
返回值为OpenerDirector对象,可调用open(url)请求url
5.HTTPCookieProcessor对象
urllib.request.HTTPCookieProcessor(cookie)
参数为cookie,返回一个Handler
cookie需要http库里的cookiejar
cookie = http.cookiejar.CookieJar()
cookie = http.cookiejar.MozillaCookieJar(filename)
cookie = http.cookiejar.LWPCookieJar(filename)
urllib.error
用来处理错误的模块,主要有两种错误URLError和HTTPError,其中HTTPError是URLError的子类。
try:
...
except HTTPError as e:
print(e.reason)
except URLError as e:
print(e.reason)
urllib.parse
用来解析url的模块
1.urlparse
url拆分
urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)
第一个参数为url
第二个参数为协议类型,url中无协议时,以该参数代替
第三个参数为fragments
2.urlunparse
url合并
urllib.parse.urlunparse(parts)
参数可以是一个list
3.urljoin
urllib.parse.urljoin(base, url)
两个参数均为url或其中的某一部分,将其合并为一个url
4.urlencode
将字典转为url的请求参数
网友评论