在使用Python的urllib库进行爬虫操作时非常繁琐,比如处理网页验证和Cookies时,需要编写Opener和Handler来处理。为了更加方便的实现这些操作,就有了更为强大的Requests库。Requests库是一个网页请求库,是基于urllib和urllib3封装的网络请求库,是目前公认的爬取网页最好的库,代码非常简洁,甚至一行代码就能爬取到网页
Requests环境配置
1 2 3 4 5
| pip install requests
import requests
|
Requests使用
requests.get
语法:requests.get(url, params=None, **kwargs)
1 2 3 4
| 实例 response = requests.get('www.baidu.com') print(response.status_code) 输出:200
|
属性 |
说明 |
.status_code |
HTTP请求返回的请求码 |
.encoding |
从HTTP Header中推测出的网页编码 |
.apparent_encoding |
从内容中分析出的网页编码 |
.text |
HTTP响应内容的字符串形式,网页源代码 |
.content |
HTTP响应内容的二进制形式 |
.json() |
对响应的内容进行json解析 |
.url |
get请求目标url |
.headers |
响应头中的相关信息 |
.request.headers |
请求头中的相关信息 |
.cookies |
请求头中的cookie |
.history |
获取所有重定向的记录 |
- headers参数
一般使用中,为了避免目标网站发现爬虫程序,一般会在请求头中设置User-Agent来让爬虫程序伪装成浏览器
1 2 3 4 5 6
| header = { 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:100.0) Gecko/20100101 Firefox/100.0' } response = requests.get('www.baidu.com', headers=header) print(response.status_code) 输出:200
|
- params参数
Requests在请求中允许使用params关键字参数,以一个字符串字典来提供这些参数。在发起请求的时候,程序会自动地将字典里的参数拼接到URL后
1 2 3 4
| param = {'q': 'python'} response = requests.get('https://search.gitee.com/', params=param) print(response.url) 输出:https://search.gitee.com/?q=python
|
- timeout参数
在爬虫中,如果没有timeout,代码可能会挂起很长时间,这个时候我们可以对请求设置timeout,让它必须在特定的时间内返回结果,否则就抛出异常
1 2 3 4
| response = requests.get('https://www.baidu.com/', timeout=0.05) print(response.status_code) 输出:requests.exceptions.ConnectTimeout
|
1 2 3 4
| response = requests.get('https://www.baidu.com/', timeout=(0.5, 0.01)) print(response.status_code) 输出:requests.exceptions.ReadTimeout
|
- proxies参数
有时,在短时间内同一ip多次访问目标URL的时候会触发网站的反爬机制,这时可以通过在发起请求时设置代理来进行规避
1 2 3
| response = requests.get('http://myip.ipip.net/') print(response.text) 输出:当前 IP:111.111.111.111 来自于:日本 东京 KDDI
|
1 2 3 4
| proxy = {'http': 'http://183.89.147.172:8080'} response = requests.get('http://myip.ipip.net/', proxies=proxy) print(response.text) 输出:当前 IP:183.89.147.172 来自于:泰国 曼谷 3bb.co.th
|
- verify参数
Requests在发送网络请求的时候,默认会验证网站的CA证书。如果当前网站没有CA证书,那么就出现SSLError
错误,我们可以用verify关键字参数,在请求的时候不验证网站的CA证书
添加verify=False
会出现InsecureRequestWarning
警告,但是不会影响后续代码的执行
1 2 3
| response = requests.get('http://data.stats.gov.cn', verify=False) print(response.status_code) 输出:200
|