发送请求
r = requests.get(‘https://api.github.com/events’)
r = requests.post(‘http://httpbin.org/post’, data = {‘key’:‘value’})
r = requests.put(‘http://httpbin.org/put’, data = {‘key’:‘value’})
r = requests.delete(‘http://httpbin.org/delete’)
r = requests.head(‘http://httpbin.org/get’)
r = requests.options(‘http://httpbin.org/get’)
传递URL参数
payload = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
r = requests.get(“http://httpbin.org/get”, params=payload)
payload = {‘key1’: ‘value1’, ‘key2’: [‘value2’, ‘value3’]}
r = requests.get(‘http://httpbin.org/get’, params=payload)
响应内容
import requests
r = requests.get(‘https://api.github.com/events’)
r.text
r.content
JSON 响应内容
r = requests.get(‘https://api.github.com/events’)
r.json()
原始响应内容
r = requests.get(‘https://api.github.com/events’, stream=True)
r.raw
定制请求头
url = ‘https://api.github.com/some/endpoint’
headers = {‘user-agent’: ‘my-app/0.0.1’}
r = requests.get(url, headers=headers)
更加复杂的 POST 请求
payload = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
r = requests.post(“http://httpbin.org/post”, data=payload)
print(r.text)
payload = ((‘key1’, ‘value1’), (‘key1’, ‘value2’))
r = requests.post(‘http://httpbin.org/post’, data=payload)
print(r.text)
import json
url = ‘https://api.github.com/some/endpoint’
payload = {‘some’: ‘data’}
r = requests.post(url, data=json.dumps(payload))
POST一个多部分编码(Multipart-Encoded)的文件
url = ‘http://httpbin.org/post’
files = {‘file’: open(‘report.xls’, ‘rb’)}
r = requests.post(url, files=files)
r.text
url = ‘http://httpbin.org/post’
files = {‘file’: (‘report.xls’, open(‘report.xls’, ‘rb’), ‘application/vnd.ms-excel’, {‘Expires’: ‘0’})}
r = requests.post(url, files=files)
r.text
url = ‘http://httpbin.org/post’
files = {‘file’: (‘report.csv’, ‘some,data,to,send\nanother,row,to,send\n’)}
r = requests.post(url, files=files)
r.text
响应状态码
r = requests.get(‘http://httpbin.org/get’)
r.status_code
r.status_code == requests.codes.ok
True
抛出异常
bad_r = requests.get(‘http://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
响应头
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’
Cookie
url = ‘http://example.com/some/cookie/setting/url’
r = requests.get(url)
r.cookies[‘example_cookie_name’]
‘example_cookie_value’
url = ‘http://httpbin.org/cookies’
cookies = dict(cookies_are=‘working’)
r = requests.get(url, cookies=cookies)
r.text
‘{“cookies”: {“cookies_are”: “working”}}’
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 = ‘http://httpbin.org/cookies’
r = requests.get(url, cookies=jar)
r.text
‘{“cookies”: {“tasty_cookie”: “yum”}}’
重定向与请求历史
r = requests.get(‘http://github.com’)
r.url
‘https://github.com/’r.status_code
200r.history
[<Response [301]>]
r = requests.get(‘http://github.com’, allow_redirects=False)
r.status_code
301r.history
[]
r = requests.head(‘http://github.com’, allow_redirects=True)
r.url
‘https://github.com/’r.history
[<Response [301]>]
超时
requests.get(‘http://github.com’, timeout=0.001)
Traceback (most recent call last):
File “”, line 1, in
requests.exceptions.Timeout: HTTPConnectionPool(host=‘github.com’, port=80): Request timed out. (timeout=0.001)
错误与异常
遇到网络问题(如:DNS 查询失败、拒绝连接等)时,>> Requests 会抛出一个 ConnectionError 异常。
如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status() 会抛出一个 HTTPError 异常。
若请求超时,则抛出一个 Timeout 异常。
若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。
所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException 。