python三方庫之requests-快速上手
基於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:異常基類。