本文基于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.contentb'[{"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請求頭:
新聞熱點
疑難解答