python requests快速上手教程
2022年7月11日大约 3 分钟约 904 字
requests是用于发送http请求的,首先需要安装:pip install requests
中文文档:点击访问
发送请求
发送请求
import requests
# -----------传递URL参数-------------
params = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get('https://www.baidu.com', params=params, timeout=5) # 字典里值为None的键不会被添加
# --------传递post表单数据------------
data = {'key1': ['value1', 'value2'], 'key': 'value'}
r = requests.post('https://httpbin.org/post', data=data, timeout=5)
# 传递json数据,(将会自当修改请求头部分内容为 application/json)
r = requests.put('https://httpbin.org/put', data=json.dumps(data), timeout=5)
r = requests.put('https://httpbin.org/put', json=data, timeout=5) # 这种方式更方便
# ------------传递文件--------------
files = {'file': open('example.xls', 'rb')} # 通常用二进制模式打开文件来传输
files = {'file': ('example.xls', open('example.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})} # 显式设置文件名/文件类型/请求头
files = {'file': ('example.txt', '这是一些数据\n这是第二行数据\n')} # 把字符串作为文件类型传输
r = requests.post('https://httpbin.org/post', files=files)
# ------------定制请求头-----------
headers = {'user-agent': 'Mozilla/5.0'}
r = requests.delete('https://httpbin.org/delete', headers=headers, timeout=5)
# ------------传递cookies---------
cookies = dict(cookies_are='working') # 方法一
cookies = requests.cookies.RequestsCookieJar() # 方法二:可以跨域名跨路径使用
cookies.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
cookies.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
r = requests.get('https://httpbin.org/cookies', cookies=cookies, timeout=5)
# ------------------------------
# 禁用默认的重定向(一般不设置)
r = requests.head('https://httpbin.org/get', allow_redirects=False, timeout=5)
# 禁用默认的SSL证书验证
r = requests.options('https://httpbin.org/get', verify=False, timeout=5)
# ----------使用会话------------
s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'key1': 'true'})
s.get('https://httpbin.org/cookies/set/sessioncookie/123456789', timeout=5)
r = s.get("https://httpbin.org/cookies", headers={'key2': 'true'}) # 会话中headers/cookie等这些不会被完全替换,想移除某值设为None,只是更新覆盖键和合并数据。在这里手动定制的不会自动复用,一次性用一次
# 前后文管理器方式使用会话,确保with区块退出后会话能被关闭
with requests.Session() as s:
s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
# 会话的好处:1.多次请求保持某些参数 2.保持cookie 3.TCP连接可能被复用,性能更好
更细致的请求
from requests import Request, Session
s = Session()
req = Request('GET', url, data=data headers=headers)
prepped = s.prepare_request(req)
# 在 prepped.body 做一些事情
# 在 prepped.headers 做一些事情
resp = s.send(prepped,
stream=stream,
verify=verify,
proxies=proxies,
cert=cert,
timeout=timeout
)
print(resp.status_code)
timeout是指连接到服务器最大超时时间,和下载内容时间无关,正式环境需要设置,如果不设置可能会遇到无限等待的情况
响应内容
from PIL import Image
import requests
from io import BytesIO
r = requests.get('https://www.baidu.com', timeout=5)
data_str = r.text # 自动推测编码并解码,也可以查看或修改 r.encoding='utf-8' 来指定编码
data_bytes = r.content # 对于图片视频等二进制内容,会自动解码gzip和deflate
i = Image.open(BytesIO(r.content)) # 字节转图片
data_object = r.json() # 对于json内容,会自动反序列化
r.status_code # 查看响应状态码
r.raise_for_status() # 如果是4XX或5XX错误,则抛出异常
r.status_code == requests.codes.ok # 判断响应码
r.url # 查看url
r.request.headers # 查看客户端请求头
r.headers # 查看服务器响应头
r.headers.get('content-type') # HTTP 头部是大小写不敏感的,参数不分大小写
# 响应内容跟的cookie
r.cookies['example_cookie_name']
# 查看重定向的类别,requests会自动重定向
Response.history
# ------------查看原始响应内容------------
r = requests.get('https://api.github.com/events', stream=True)
r.raw # 方式一:原始字节流,它不转换响应内容。请求必须加stream字段
r.raw.read(10)
r.iter_content # (推荐)方式二:流式下载时自动解码gzip和deflate传输编码的内容,而raw不会。
# 通常您应该使用这样的模式来保存流到文件中的内容
with open(filename, 'wb') as fd:
for chunk in r.iter_content(chunk_size=128):
fd.write(chunk)
其他内容
https://zhuanlan.zhihu.com/p/267324654
https://zhuanlan.zhihu.com/p/267705727
https://zhuanlan.zhihu.com/p/267751818