python三方庫之requests-快速上手

基於2.21.0nginx

發送請求

發送GET請求:git

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

發送POST請求:github

r = requests.post('https://httpbin.org/post', data={'key':'value'})

其餘請求接口與HTTP請求類型一致,如PUT, DELETE, HEAD, OPTIONS等。json

在URL查詢字符串中使用參數

params參數傳遞一個字典對象:api

>>> 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的鍵值對不會加到查詢字符串cookie

文本響應內容

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使用的編碼:app

>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'

二進制響應內容

Response對象的content屬性能夠獲取服務器響應內容的二進制形式:dom

>>> 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方法將自動解碼gzipdeflate傳輸編碼:

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, bytestringunicode類型。但建議儘可能避免傳遞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) 若是在請求中使用了datafiles參數,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:異常基類。

相關文章
相關標籤/搜索