一、定制请求头
定义headers
,类型为dict
import requests
url = 'https://api.douban.com/v2/book/search?q=小王子'
headers={'user-agent': 'Mozilla/5.0'}
r = requests.get(url,headers=headers)
注:Requests 不会基于定制 header 的具体情况改变自己的行为。只不过在最后的请求中,所有的 header 信息都会被传递进去,如下图的请求头信息按照需求都可以这样子传递
二、更加复杂的POST请求
在上一篇文章中可以传递带参数的get请求,只需要在url后添加一个params
参数即可,下面展示更加复杂的post请求
1、传递一些编码为表单形式的数据——非常像一个 HTML 表单。要实现这个,只需简单地传递一个字典给 data
参数。你的数据字典在发出请求时会自动编码为表单形式
import requests
payload={'key1':'value1','key2':'value2'} #参数为dict形式
r=requests.post("http://httpbin.org/post",data=payload)
print(r.url)
print(r.text)
>>http://httpbin.org/post #输出url
>>{
...
...
"form": {
"key1": "value1",
"key2": "value2"
},
"headers": {
"Accept": "*/*",
... ...
}
}
data参数为元组形式,可传递一个key值包含多个值的参数
import requests
payload=(('key1','value1'),('key1','value2')) #参数为元组
r=requests.post("http://httpbin.org/post",data=payload)
print(r.url)
print(r.text)
>>http://httpbin.org/post
>>{
... ...
"form": {
"key1": [
"value1",
"value2"
]
},
"headers": {
"Accept": "*/*",
... ...
}
}
2、很多时候你想要发送的数据并非编码为表单形式的。如果你传递一个 string 而不是一个 dict
import requests
import json
payload={'some':'data'}
url = 'http://httpbin.org/post'
r=requests.post(url,data=json.dumps(payload))
import requests
payload={'some':'data'}
url = 'http://httpbin.org/post'
r=requests.post(url,json=payload)
{
... ...
"json": {
"some": "data"
},
... ...
}
3、post一个多部分编码的文件
import requests
url='http://httpbin.org/post'
path = r'E:\history.txt'
files={'file':open(path,'rb')}
r = requests.post(url,files=files) #参数为一个文件
print(r.url)
print(r.text)
>>http://httpbin.org/post
>>{
... ...
"files": {
"file": "data:application/octet-stream;base64,gANjY29sbGVjdGlvbnMKZGVxdWUKcQBdcQEoSyJLOEtNS0JLRmVLBYZxAlJxAy4="
},
... ...
}
可以显示的设置文件名、文件类型和请求头
import requests
url='http://httpbin.org/post'
path = r'E:\history.txt'
files={'file':('report.xls',open(path,'rb'),'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url,files=files)
>> "files": {
"file": "data:application/vnd.ms-excel;base64,gANjY29sbGVjdGlvbnMKZGVxdWUKcQBdcQEoSyJLOEtNS0JLRmVLBYZxAlJxAy4="
},
也可以发送作为文件来接收的字符串