1 前言
官网中对requests的介绍是"HTTP for Humans"
Requests allows you to send organic, grass-fed HTTP/1.1 requests, without the need for manual labor. There’s no need to manually add query strings to your URLs, or to form-encode your POST data. Keep-alive and HTTP connection pooling are 100% automatic, thanks to urllib3.
GET请求不用&拼接参数,POST请求也毋须编码请求体
总之简单易用,是接口测试和爬虫的必备神器
2 基本使用
2-1 get/post
import requests
//get无参数
r = requests.get('https://httpbin.org/get')
//get有参数,使用params
data = {'key': 'value'}
r = requests.get('https://httpbin.org/get', params=data)
//post有参数,使用data
r = requests.post('https://httpbin.org/post', data = {'key':'value'})
2-2 自定义请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36'
}
r = requests.get('https://httpbin.org/get', headers=headers)
2-3 响应内容
r.content 响应内容的字节码,一般处理二进制文件
r.text 自动选择适当的编码,对r.content解码
r.json() 解析json格式的数据,如果无法解析,则抛出异常
3 API
无论是get/post/delete/put/patch/head/options,都是调用request方法
参数如下:
url 请求的URL地址
params GET请求参数
data POST请求参数
json 同样是POST请求参数,要求服务端接收json格式的数据
headers 请求头字典
cookies cookies信息(字典或CookieJar)
files 上传文件
auth HTTP鉴权信息
timeout 等待响应时间,单位秒
allow_redirects 是否允许重定向
proxies 代理信息
verify 是否校验证书
stream 如果为False,则响应内容将直接全部下载
cert 客户端证书地址
4 Session对象
Session可以持久化请求过程中的参数,以及cookie
尤其是需要登录的网页,使用session可以避免每次的登录操作
s = requests.Session()
s.cookies = requests.cookies.cookiejar_from_dict({'key': 'value'})
r = s.get('https://httpbin.org/cookies')
print(r.text)
===========================
{
"cookies": {
"key": "value"
}
}
另外session还可提供默认值
s = requests.Session()
s.headers.update({'h1':'val1', 'h2':'val2'})
r = s.get('https://httpbin.org/headers', headers={'h2': 'val2_modify'})
print(r.text)
============================
"H1": "val1",
"H2": "val2_modify",
5 Response对象
字段
cookies 返回CookieJar对象
encoding 报文的编码
headers 响应头
history 重定向的历史记录
status_code 响应状态码,如200
elaspsed 发送请求到接收响应耗时
text 解码后的报文主体
content 字节码,可能在raw的基础上解压
方法
json() 解析json格式的响应
iter_content() 需配置stream=True,指定chunk_size大小
iter_lines() 需配置stream=True,每次返回一行
raise_for_status() 400-500之间将抛出异常
close()
6 Prepared Requests
一般情况下,会一次性包装好请求头,请求参数,cookies,鉴权等;但如果通过某些条件判断,可以局部组装requests
s = requests.Session()
req = requests.Request('GET', url='https://httpbin.org/get')
prep = s.prepare_request(req)
headers = {
'User-Agent': 'Chrome/67.0.3396.62'
}
prep.prepare(
method='POST',
url='https://httpbin.org/post',
headers=headers,
data={'key': 'value'}
)
r = s.send(prep)
print(r.text)
===================
{
"args": {},
"data": "",
"files": {},
"form": {
"key": "value"
},
"headers": {
"Accept-Encoding": "identity",
"Connection": "close",
"Content-Length": "9",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Chrome/67.0.3396.62"
},
"json": null,
"origin": "xx.xx.xx.xx",
"url": "https://httpbin.org/post"
}