本文基于2.21.0
发送请求
发送GET请求:
r = requests.get('https://api.github.com/events')
发送POST请求:
r = requests.post('https://httpbin.org/post', data={'key':'value'})
其他请求接口与HTTP请求类型一致,如PUT, DELETE, HEAD, OPTIONS等。
在URL查询字符串中使用参数
给params参数传递一个字典对象:
>>> 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
字典的值也可以是一个列表:
>>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}>>> r = requests.get('https://httpbin.org/get', params=payload)>>> print(r.url)https://httpbin.org/get?key1=value1&key2=value2&key2=value3
参数中值为None的键值对不会加到查询字符串
文本响应内容
Response对象的text属性可以获取服务器响应内容的文本形式,Requests会自动解码:
>>> r = requests.get('https://api.github.com/events')>>> r.text'[{"id":"9167113775","type":"PushEvent","actor"...
访问Response.text时,Requests将基于HTTP头猜测响应内容编码。使用Response.encoding属性可以查看或改变Requests使用的编码:
>>> r.encoding'utf-8'>>> r.encoding = 'ISO-8859-1'
二进制响应内容
Response对象的content属性可以获取服务器响应内容的二进制形式:
>>> r.contentb'[{"id":"9167113775","type":"PushEvent","actor"...
JSON响应内容
Response对象的json()方法可以获取服务器响应内容的JSON形式:
>>> r = requests.get('https://api.github.com/events')>>> r.json()[{'repo': {'url': 'https://api.github.com/...
如果JSON解码失败,将抛出异常。
原始响应内容
在极少情况下,可能需要访问服务器原始套接字响应。通过在请求中设置stream=True参数,并访问Response对象的raw属性实现:
>>> r = requests.get('https://api.github.com/events', stream=True)>>> r.raw<urllib3.response.HTTPResponse object at 0x101194810>>>> r.raw.read(10)'/x1f/x8b/x08/x00/x00/x00/x00/x00/x00/x03'
通常的用法是用下面这种方式将原始响应内容保存到文件,Response.iter_content方法将自动解码gzip和deflate传输编码:
with open(filename, 'wb') as fd: for chunk in r.iter_content(chunk_size=128): fd.write(chunk)
定制请求头
传递一个dict对象到headers参数,可以添加HTTP请求头:
新闻热点
疑难解答