urllib库:用来处理网络请求的python标准库
主要包含4个模块:
- urllib.requests:请求模块,用来发起网络请求
- urllib.parse:解析模块,用来解析url
- urllib.error:异常处理模块,用来处理requests引起的异常情况
- urllib.robotparse:用来解析robots.txt文件
1.requests模块
主要负责构造和发起网络请求,并在其中添加headers、proxy等。利用requests模块可以模拟浏览器的请求发起过程。
1.1 请求方法urlopen
"urlopen是一个简单的发送网络请求的方法,timeout设置超时,如果请求超过设置时间,则抛出异常" response = request.urlopen(url='http://www.baidu.com/get', timeout=0.1) "urlopen默认是发送get请求,当传入data参数时,则会发送post请求" response = request.urlopen(url='http://www.baidu.com/post',data=b'username=admin&password=123456')
1.2 添加请求头
"通过urllib发送的请求会有一个默认的Headers: “User-Agent”:“Python-urllib/3.6”,指明请求是由urllib发送的。"
"所以遇到一些验证User-Agent的网站时,需要我们自定义Headers把自己伪装起来。"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/71.0.3578.98 Safari/537.36'
}
req = request.Request('http://www.baidu.com', headers=headers)
1.3 操作cookie
from urllib import request
from http import cookiejar
# 创建一个cookie对象
cookie = cookiejar.CookieJar()
# 创建一个cookie处理器
cookies = request.HTTPCookieProcessor(cookie)
# 以cookies为参数,创建openner对象
opener = request.build_opener(cookies)
# 使用opener来发送请求
res = opener.open('http://www.baidu.com')
print(cookies.cookiejar)
1.4 设置代理
from urllib import request
url = 'http://www.baidu.com'
# 代理地址
proxy = {'http': '192.168.0.105:8080'}
# 代理服务器
proxies = request.ProxyHandler(proxy)
# 创建opnner对象
opener = request.build_opener(proxies)
res = opener.open(url)
print(res.read().decode())
1.5 response对象
"urllib库中的类或方法,用来处理返回的结果"
# read():获取响应返回的数据,只能用一次
print(response.read())
# readline():读取一行
wile True
data = response.readline()
if data:
print(data)
# info():获取响应头信息
print(response.info())
# 获取访问的url
print(response.geturl())
# 返回状态码
print(response.getcode())
2.parse模块
提供需要对url处理的方法,用于解析url
# parse.quote()------编码特殊字符
"url中只能包含ascii字符,在实际操作过程中,get请求通过url传递的参数中会有大量的特殊字符,例如汉字,那么就需要进行url编码。"
from urllib import parse
url = 'https://www.baidu.com/s?wd={}'
safe_url = url.format(parse.quote('杭州'))
print(safe_url)
# 利用parse.unquote进行返编码
safe1_url = url.format(parse.unquote(safe_url))
print(safe1_url)
# parse.urlencode()------拼接url参数
params = {'wd': '测试', 'code': 1, 'height': '188'}
res = parse.urlencode(params)
print(res)
# 使用parse.parse_qs()方法将它转回字典
print(parse.parse_qs(res))
3.error模块
主要负责处理异常,如果请求出现错误,可以利用error模块进行处理主要包含URLError和HTTPError
URLError:是error异常模块的基类,由request模块产生的异常都可以用这个类来处理。
HTTPError:是URLError的子类,主要包含三个属性:
- code:请求的状态码
- reason:错误的原因
- headers:响应的报头
4.robotparse模块
主要负责处理爬虫协议文件:robots.txt的解析。http://www.taobao.com/robots.txt
来源:https://www.cnblogs.com/Cyzhouke/p/11498659.html