requests高级用法
1.session会话
保持会话的请求,保持请求后的状态,且能传递cookie
import requests
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")
print(r.text)
# 输出
{
"cookies": {
"sessioncookie": "123456789"
}
}
2.请求响应对象
拿到headers明信片
r = requests.get('http://httpbin.org/ip')
print(r.headers)
# 输出
{'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Origin': '*', 'Content-Encoding': 'gzip', 'Content-Type': 'application/json', 'Date': 'Wed, 04 Dec 2019 13:10:29 GMT', 'Referrer-Policy': 'no-referrer-when-downgrade', 'Server': 'nginx', 'X-Content-Type-Options': 'nosniff', 'X-Frame-Options': 'DENY', 'X-XSS-Protection': '1; mode=block', 'Content-Length': '57', 'Connection': 'keep-alive'}
3.文件上传
import requests
file = {"file": open('a.jpg', 'rb')}
response = requests.post('http://www.httpbin.org/post', files=file)
print(response.json())
# 输出
官方文档
https://2.python-requests.org//zh_CN/latest/user/advanced.html