requests是一个很实用的Python HTTP客户端库,爬虫和测试服务器响应数据时经常会用到,requests是Python语言的第三方的库,专门用于发送HTTP请求,使用起来比urllib简洁很多。
Requests 有这些功能:
1、Keep-Alive & 连接池
2、国际化域名和 URL
3、带持久 Cookie 的会话
4、浏览器式的 SSL 认证
5、自动内容解码
6、基本/摘要式的身份认证
7、优雅的 key/value Cookie
8、自动解压
9、Unicode 响应体
10、HTTP(S) 代理支持
11、文件分块上传
12、流下载
13、连接超时
14、分块请求
15、支持 .netrc
Requests 支持 Python 2.6—2.7以及3.3—3.7,而且能在 PyPy 下完美运行。
用pip进行第三方库的安装
1
|
pip install requests |
安装完成后import一下,正常则说明可以开始使用了。
二、基本用法:
1、requests.get()
用于请求目标网站,类型是一个HTTPresponse类型
1
2
3
4
5
6
7
8
9
10
11
|
import requests response = requests.get( 'http://www.baidu.com' ) print (response.status_code) # 打印状态码 print (response.url) # 打印请求url print (response.headers) # 打印头信息 print (response.cookies) # 打印cookie信息 print (response.text) #以文本形式打印网页源码 print (response.content) #以字节流形式打印 print (response.content.decode( "utf-8" )) #解决了通过response.text直接返回显示乱码的问题 response.encoding = "utf-8" #避免乱码的问题发生 |
2、各种请求方式
1
2
3
4
5
6
7
8
|
import requests requests.get( 'http://httpbin.org/get' ) requests.post( 'http://httpbin.org/post' ) requests.put( 'http://httpbin.org/put' ) requests.delete( 'http://httpbin.org/delete' ) requests.head( 'http://httpbin.org/get' ) requests.options( 'http://httpbin.org/get' ) |
3、基本的get请求
1
2
3
4
|
import requests response = requests.get( 'http://httpbin.org/get' ) print (response.text) |
4、带参数的get请求
第一种直接将参数放在url内
1
2
3
4
|
import requests response = requests.get(http: / / httpbin.org / get?name = gemey&age = 22 ) print (response.text) |
另一种先将参数填写在dict中,发起请求时params参数指定为dict
1
2
3
4
5
6
7
8
|
import requests data = { 'name' : 'tom' , 'age' : 20 } response = requests.get( 'http://httpbin.org/get' , params = data) print (response.text) |
5、解析json
1
2
3
4
5
6
|
import requests response = requests.get( 'http://httpbin.org/get' ) print (response.text) print (response.json()) #response.json()方法同json.loads(response.text) print ( type (response.json())) |
如果 JSON 解码失败, 将会抛出 ValueError: No JSON object could be decoded 异常。而成功调用 response.json() 并不意味着响应的成功。有的服务器会在失败的响应中包含一个 JSON 对象(比如 HTTP 500 的错误细节)。这种 JSON 会被解码返回。要检查请求是否成功,请使用 r.raise_for_status() 或者检查 response.status_code 是否和你的期望相同
6、保存一个二进制文件
二进制内容为response.content
1
2
3
4
5
6
|
import requests response = requests.get( 'http://img.ivsky.com/img/tupian/pre/201708/30/kekeersitao-002.jpg' ) b = response.content with open ( 'F://fengjing.jpg' , 'wb' ) as f: f.write(b) |
7、添加heads信息
1
2
3
4
5
6
|
import requests heads = {} heads[ 'User-Agent' ] = 'Mozilla/5.0 ' \ '(Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 ' \ '(KHTML, like Gecko) Version/5.1 Safari/534.50' response = requests.get( 'http://www.baidu.com' ,headers = headers) |
8、使用代理
同添加headers方法,代理参数也要是一个dict
这里使用requests库爬取了IP代理网站的IP与端口和类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
import requests import re def get_html(url): proxy = { 'http' : '120.25.253.234:812' , 'https' : '163.125.222.244:8123' } heads = {} heads[ 'User-Agent' ] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0' req = requests.get(url, headers = heads,proxies = proxy) html = req.text return html def get_ipport(html): regex = r '<td data-title="IP">(.+)</td>' iplist = re.findall(regex, html) regex2 = '<td data-title="PORT">(.+)</td>' portlist = re.findall(regex2, html) regex3 = r '<td data-title="类型">(.+)</td>' typelist = re.findall(regex3, html) sumray = [] for i in iplist: for p in portlist: for t in typelist: pass pass a = t + ',' + i + ':' + p sumray.append(a) print ( '高匿代理' ) print (sumray) if __name__ = = '__main__' : url = 'http://www.kuaidaili.com/free/' get_ipport(get_html(url)) |
9、基本POST请求
1
2
3
4
5
|
import requests data = { 'name' : 'tom' , 'age' : '22' } response = requests.post( 'http://httpbin.org/post' , data = data) |
10、获取cookie
1
2
3
4
5
6
7
|
import requests response = requests.get( 'http://www.baidu.com' ) print (response.cookies) print ( type (response.cookies)) for k,v in response.cookies.items(): print (k + ':' + v) |
11、会话维持
1
2
3
4
5
6
|
import requests session = requests.Session() session.get( 'http://httpbin.org/cookies/set/number/12345' ) response = session.get( 'http://httpbin.org/cookies' ) print (response.text) |
11、证书验证设置
import requests
from requests.packages import urllib3
urllib3.disable_warnings() #从urllib3中消除警告
response = requests.get('https://www.scratch.net.cn',verify=False) #证书验证设为FALSE
print(response.status_code)
12、超时异常捕获
import requests
from requests.exceptions import ReadTimeout
try:
res = requests.get('http://www.scratch.net.cn', timeout=0.1)
print(res.status_code)
except ReadTimeout:
print(timeout)
13、异常处理
在你不确定会发生什么错误时,尽量使用try…except来捕获异常
import requests from requests.exceptions import ReadTimeout,HTTPError,RequestException try: response = requests.get('http://www.scratch.net.cn',timeout=0.5) print(response.status_code) except ReadTimeout: print('timeout') except HTTPError: print('httperror') except RequestException: print('reqerror')
-
扫码下载安卓APP
-
微信扫一扫关注我们
微信扫一扫打开小程序
手Q扫一扫打开小程序
-
返回顶部
发表评论