python三方库之requests-快速上手

26次阅读

共计 5682 个字符,预计需要花费 15 分钟才能阅读完成。

基于 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.content
b'[{“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 请求头:
>>> url = ‘https://api.github.com/some/endpoint’
>>> headers = {‘user-agent’: ‘my-app/0.0.1’}

>>> r = requests.get(url, headers=headers)
定制的 header 的优先级较低,在某些场景或条件下可能被覆盖。
所有 header 的值必须是 string, bytestring 或 unicode 类型。但建议尽量避免传递 unicode 类型的值
更复杂的 POST 请求
发送 form-encoded 数据
给 data 参数传递一个字典对象:
>>> payload = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
>>> r = requests.post(“https://httpbin.org/post”, data=payload)
如果有多个值对应一个键,可以使用由元组组成的列表或者值是列表的字典:
>>> payload_tuples = [(‘key1’, ‘value1’), (‘key1’, ‘value2’)]
>>> r1 = requests.post(‘https://httpbin.org/post’, data=payload_tuples)
>>> payload_dict = {‘key1’: [‘value1’, ‘value2’]}
>>> r2 = requests.post(‘https://httpbin.org/post’, data=payload_dict)
发送非 form-encoded 数据
如果传递的是字符串而非字典,将直接发送该数据:
>>> import json
>>> url = ‘https://api.github.com/some/endpoint’
>>> payload = {‘some’: ‘data’}
>>> r = requests.post(url, data=json.dumps(payload))
或者可以使用 json 参数自动对字典对象编码:
>>> url = ‘https://api.github.com/some/endpoint’
>>> payload = {‘some’: ‘data’}
>>> r = requests.post(url, json=payload)
a) 如果在请求中使用了 data 或 files 参数,json 参数会被忽略。b) 在请求中使用 json 参数会改变 Content-Type 的值为 application/json
POST 一个多部分编码 (Multipart-Encoded) 的文件
上传文件:
>>> url = ‘https://httpbin.org/post’
>>> files = {‘file’: open(‘report.xls’, ‘rb’)}
>>> r = requests.post(url, files=files)
显式地设置文件名,内容类型 (Content-Type) 以及请求头:
>>> url = ‘https://httpbin.org/post’
>>> files = {‘file’: (‘report.xls’, open(‘report.xls’, ‘rb’), ‘application/vnd.ms-excel’, {‘Expires’: ‘0’})}
>>> r = requests.post(url, files=files)
甚至可以发送作为文件接收的字符串:
>>> url = ‘http://httpbin.org/post’
>>> files = {‘file’: (‘report.csv’, ‘some,data,to,send\nanother,row,to,send\n’)}
>>> r = requests.post(url, files=files)
如果发送的文件过大,建议使用第三方包 requests-toolbelt 做成数据流。
强烈建议以二进制模式打开文件,因为 Requests 可能以文件中的字节长度来设置 Content-Length
响应状态码
Response 对象的 status_code 属性可以获取响应状态:
>>> r = requests.get(‘https://httpbin.org/get’)
>>> r.status_code
200
requests 库还内置了状态码以供参考:
>>> r.status_code == requests.codes.ok
True
如果请求异常 (状态码为 4XX 的客户端错误或 5XX 的服务端错误),可以调用 raise_for_status() 方法抛出异常:
>>> bad_r = requests.get(‘https://httpbin.org/status/404’)
>>> bad_r.status_code
404
>>> bad_r.raise_for_status()
Traceback (most recent call last):
File “requests/models.py”, line 832, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error
响应头
Response 对象的 headers 属性可以获取响应头,它是一个字典对象,键不区分大小写:
>>> r.headers
{
‘content-encoding’: ‘gzip’,
‘transfer-encoding’: ‘chunked’,
‘connection’: ‘close’,
‘server’: ‘nginx/1.0.4’,
‘x-runtime’: ‘148ms’,
‘etag’: ‘”e1ca502697e5c9317743dc078f67693f”‘,
‘content-type’: ‘application/json’
}
>>> r.headers[‘Content-Type’]
‘application/json’
>>> r.headers.get(‘content-type’)
‘application/json’
Cookies
Response 对象的 cookies 属性可以获取响应中的 cookie 信息:
>>> url = ‘http://example.com/some/cookie/setting/url’
>>> r = requests.get(url)
>>> r.cookies[‘example_cookie_name’]
‘example_cookie_value’
使用 cookies 参数可以发送 cookie 信息:
>>> url = ‘https://httpbin.org/cookies’
>>> cookies = dict(cookies_are=’working’)
>>> r = requests.get(url, cookies=cookies)
Response.cookies 返回的是一个 RequestsCookieJar 对象,跟字典类似但提供了额外的接口,适合多域名或多路径下使用,也可以在请求中传递:
>>> jar = requests.cookies.RequestsCookieJar()
>>> jar.set(‘tasty_cookie’, ‘yum’, domain=’httpbin.org’, path=’/cookies’)
>>> jar.set(‘gross_cookie’, ‘blech’, domain=’httpbin.org’, path=’/elsewhere’)
>>> url = ‘https://httpbin.org/cookies’
>>> r = requests.get(url, cookies=jar)
>>> r.text
‘{“cookies”: {“tasty_cookie”: “yum”}}’
重定向及请求历史
requests 默认对除 HEAD 外的所有请求执行地址重定向。Response.history 属性可以追踪重定向历史,它返回一个 list,包含为了完成请求创建的所有 Response 对象并由老到新排序。
下面是一个 HTTP 重定向 HTTPS 的用例:
>>> r = requests.get(‘http://github.com/’)
>>> r.url
‘https://github.com/’
>>> r.status_code
200
>>> r.history
[<Response [301]>]
使用 allow_redirects 参数可以禁用重定向:
>>> r = requests.get(‘http://github.com/’, allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]
如果使用的是 HEAD 请求,也可以使用 allow_redirects 参数允许重定向:
>>> r = requests.head(‘http://github.com/’, allow_redirects=True)
>>> r.url
‘https://github.com/’
>>> r.history
[<Response [301]>]
请求超时
使用 timeout 参数设置服务器返回响应的最大等待时间:
>>> requests.get(‘https://github.com/’, timeout=0.001)
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host=’github.com’, port=80): Request timed out. (timeout=0.001)
错误及异常
ConnectionError:网络异常,比如 DNS 错误,连接拒绝等。HTTPError:如果请求返回 4XX 或 5XX 状态码,调用 Response.raise_for_status()会抛出此异常。Timeout:连接超时。TooManyRedirects:请求超过配置的最大重定向数。RequestException:异常基类。

正文完
 0