python-requests库文档学习

发布时间 2023-04-06 15:13:49作者: niko5960

quickstart

英文文档:https://requests.readthedocs.io/en/latest/user/quickstart/

Passing Parameters In URLs在url中手动传递参数

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('https://httpbin.org/get', params=payload)
print(r.url)
https://httpbin.org/get?key2=value2&key1=value1
输出的内容自动带上参数

Response Content指定编码

url = "http://www.innofund.gov.cn/zxqyfw/gongg/yjlist.shtml"
a = requests.get(url)
#指定了编码格式,输出的内容将以指定的格式输出
a.encoding = "ISO-8859-1"
print(a.encoding)	
#这个地方可以打印出现在使用的编码,如果之前没有指定,那么会打印出来猜测的编码
print(a.text)

Binary Response Content二进制的响应内容

reuqest.content这个方法返回的是二进制的内容,通过二进制内容可以处理非文本请求
处理一张图片

from PIL import Image
from io import BytesIO

i = Image.open(BytesIO(r.content))

json响应内容

调用json方法直接处理json数据

import requests

r = requests.get('https://api.github.com/events')
r.json()

注意,有的网站会在请求失败的时候也会返回json,比如有的会返回状态码500,这样的响应数据也会被解码成json,使用的时候应该配合r.raise_for_status()r.status_code来判断状态码

It should be noted that the success of the call to r.json() does not indicate the success of the response. Some servers may return a JSON object in a failed response (e.g. error details with HTTP 500). Such JSON will be decoded and returned. To check that a request is successful, use r.raise_for_status() or check r.status_code is what you expect.

解码不成功的时候会返回requests.exceptions.JSONDecodeError错误

原始响应内容:套接字

处理套接字,设置参数stream=True,使用r.raw

r = requests.get('https://api.github.com/events', stream=True)

r.raw