requests

熊大2022年7月11日大约 3 分钟

requests是用于发送http请求的,首先需要安装:pip install requests

中文文档:点击访问open in new window

发送请求

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