本文基于2.21.0
發(fā)送請(qǐng)求
發(fā)送GET請(qǐng)求:
r = requests.get('https://api.github.com/events')發(fā)送POST請(qǐng)求:
r = requests.post('https://httpbin.org/post', data={'key':'value'})其他請(qǐng)求接口與HTTP請(qǐng)求類型一致,如PUT, DELETE, HEAD, OPTIONS等。
在URL查詢字符串中使用參數(shù)
給params參數(shù)傳遞一個(gè)字典對(duì)象:
>>> 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字典的值也可以是一個(gè)列表:
>>> 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參數(shù)中值為None的鍵值對(duì)不會(huì)加到查詢字符串
文本響應(yīng)內(nèi)容
Response對(duì)象的text屬性可以獲取服務(wù)器響應(yīng)內(nèi)容的文本形式,Requests會(huì)自動(dòng)解碼:
>>> r = requests.get('https://api.github.com/events')>>> r.text'[{"id":"9167113775","type":"PushEvent","actor"...訪問Response.text時(shí),Requests將基于HTTP頭猜測(cè)響應(yīng)內(nèi)容編碼。使用Response.encoding屬性可以查看或改變Requests使用的編碼:
>>> r.encoding'utf-8'>>> r.encoding = 'ISO-8859-1'
二進(jìn)制響應(yīng)內(nèi)容
Response對(duì)象的content屬性可以獲取服務(wù)器響應(yīng)內(nèi)容的二進(jìn)制形式:
>>> r.contentb'[{"id":"9167113775","type":"PushEvent","actor"...JSON響應(yīng)內(nèi)容
Response對(duì)象的json()方法可以獲取服務(wù)器響應(yīng)內(nèi)容的JSON形式:
>>> r = requests.get('https://api.github.com/events')>>> r.json()[{'repo': {'url': 'https://api.github.com/...如果JSON解碼失敗,將拋出異常。
原始響應(yīng)內(nèi)容
在極少情況下,可能需要訪問服務(wù)器原始套接字響應(yīng)。通過在請(qǐng)求中設(shè)置stream=True參數(shù),并訪問Response對(duì)象的raw屬性實(shí)現(xiàn):
>>> 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'通常的用法是用下面這種方式將原始響應(yīng)內(nèi)容保存到文件,Response.iter_content方法將自動(dòng)解碼gzip和deflate傳輸編碼:
with open(filename, 'wb') as fd: for chunk in r.iter_content(chunk_size=128): fd.write(chunk)
定制請(qǐng)求頭
傳遞一個(gè)dict對(duì)象到headers參數(shù),可以添加HTTP請(qǐng)求頭:
>>> url = 'https://api.github.com/some/endpoint'>>> headers = {'user-agent': 'my-app/0.0.1'}>>> r = requests.get(url, headers=headers)定制的header的優(yōu)先級(jí)較低,在某些場(chǎng)景或條件下可能被覆蓋。
所有header的值必須是string, bytestring或unicode類型。但建議盡量避免傳遞unicode類型的值
更復(fù)雜的POST請(qǐng)求
發(fā)送form-encoded數(shù)據(jù)
給data參數(shù)傳遞一個(gè)字典對(duì)象:
>>> payload = {'key1': 'value1', 'key2': 'value2'}>>> r = requests.post("https://httpbin.org/post", data=payload)如果有多個(gè)值對(duì)應(yīng)一個(gè)鍵,可以使用由元組組成的列表或者值是列表的字典:
>>> 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)發(fā)送非form-encoded數(shù)據(jù)
如果傳遞的是字符串而非字典,將直接發(fā)送該數(shù)據(jù):
>>> import json>>> url = 'https://api.github.com/some/endpoint'>>> payload = {'some': 'data'}>>> r = requests.post(url, data=json.dumps(payload))或者可以使用json參數(shù)自動(dòng)對(duì)字典對(duì)象編碼:
>>> url = 'https://api.github.com/some/endpoint'>>> payload = {'some': 'data'}>>> r = requests.post(url, json=payload)a) 如果在請(qǐng)求中使用了data或files參數(shù),json參數(shù)會(huì)被忽略。b) 在請(qǐng)求中使用json參數(shù)會(huì)改變Content-Type的值為application/json
POST一個(gè)多部分編碼(Multipart-Encoded)的文件
上傳文件:
>>> url = 'https://httpbin.org/post'>>> files = {'file': open('report.xls', 'rb')}>>> r = requests.post(url, files=files)顯式地設(shè)置文件名,內(nèi)容類型(Content-Type)以及請(qǐng)求頭:
>>> 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)甚至可以發(fā)送作為文件接收的字符串:
>>> url = 'http://httpbin.org/post'>>> files = {'file': ('report.csv', 'some,data,to,send/nanother,row,to,send/n')}>>> r = requests.post(url, files=files)如果發(fā)送的文件過大,建議使用第三方包requests-toolbelt做成數(shù)據(jù)流。
強(qiáng)烈建議以二進(jìn)制模式打開文件,因?yàn)镽equests可能以文件中的字節(jié)長(zhǎng)度來設(shè)置Content-Length
響應(yīng)狀態(tài)碼
Response對(duì)象的status_code屬性可以獲取響應(yīng)狀態(tài):
>>> r = requests.get('https://httpbin.org/get')>>> r.status_code200requests庫還內(nèi)置了狀態(tài)碼以供參考:
>>> r.status_code == requests.codes.okTrue
如果請(qǐng)求異常(狀態(tài)碼為4XX的客戶端錯(cuò)誤或5XX的服務(wù)端錯(cuò)誤),可以調(diào)用raise_for_status()方法拋出異常:
>>> bad_r = requests.get('https://httpbin.org/status/404')>>> bad_r.status_code404>>> bad_r.raise_for_status()Traceback (most recent call last): File "requests/models.py", line 832, in raise_for_status raise http_errorrequests.exceptions.HTTPError: 404 Client Error響應(yīng)頭
Response對(duì)象的headers屬性可以獲取響應(yīng)頭,它是一個(gè)字典對(duì)象,鍵不區(qū)分大小寫:
>>> 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對(duì)象的cookies屬性可以獲取響應(yīng)中的cookie信息:
>>> url = 'http://example.com/some/cookie/setting/url'>>> r = requests.get(url)>>> r.cookies['example_cookie_name']'example_cookie_value'
使用cookies參數(shù)可以發(fā)送cookie信息:
>>> url = 'https://httpbin.org/cookies'>>> cookies = dict(cookies_are='working')>>> r = requests.get(url, cookies=cookies)
Response.cookies返回的是一個(gè)RequestsCookieJar對(duì)象,跟字典類似但提供了額外的接口,適合多域名或多路徑下使用,也可以在請(qǐng)求中傳遞:
>>> 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"}}'重定向及請(qǐng)求歷史
requests默認(rèn)對(duì)除HEAD外的所有請(qǐng)求執(zhí)行地址重定向。Response.history屬性可以追蹤重定向歷史,它返回一個(gè)list,包含為了完成請(qǐng)求創(chuàng)建的所有Response對(duì)象并由老到新排序。
下面是一個(gè)HTTP重定向HTTPS的用例:
>>> r = requests.get('http://github.com/')>>> r.url'https://github.com/'>>> r.status_code200>>> r.history[<Response [301]>]使用allow_redirects參數(shù)可以禁用重定向:
>>> r = requests.get('http://github.com/', allow_redirects=False)>>> r.status_code301>>> r.history[]如果使用的是HEAD請(qǐng)求,也可以使用allow_redirects參數(shù)允許重定向:
>>> r = requests.head('http://github.com/', allow_redirects=True)>>> r.url'https://github.com/'>>> r.history[<Response [301]>]請(qǐng)求超時(shí)
使用timeout參數(shù)設(shè)置服務(wù)器返回響應(yīng)的最大等待時(shí)間:
>>> 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)錯(cuò)誤及異常
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選