1. 程式人生 > >python-requests簡單介紹及用法

python-requests簡單介紹及用法

requests是一個很實用的 HTTP客戶端庫,編寫爬蟲和測試伺服器響應資料時經常會用到。可以說,Requests 完全滿足如今網路的需求

本文全部來源於官方文件 http://docs.python-requests.org/en/master/

安裝方式一般採用$ pip install requests。其它安裝方式參考官方文件

HTTP - requests

import requests

GET請求

r  = requests.get('http://httpbin.org/get')

傳參

>>> payload {'key1''value1''key2''value2', 'key3'

: None}>>> requests.get('http://httpbin.org/get'params=payload)

Note that any dictionary key whose value is None will not be added to the URL's query string.

引數也可以傳遞列表

>>> payload {'key1''value1''key2': ['value2''value3']}

r.text 返回headers中的編碼解析的結果,可以通過r.encoding = 'gbk'來變更解碼方式

r.content返回二進位制結果

r.json()返回JSON格式,可能丟擲異常

r.status_code

r.raw返回原始socket respons,需要加引數stream=True

>>> requests.get('https://api.github.com/events'stream=True)

>>> r.raw<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>

>>> r.raw.read(10)'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'

將結果儲存到檔案,利用r.iter_content()

with open(filename'wb'as fd:for chunk in r.iter_content(chunk_size):fd.write(chunk)

傳遞headers

>>> headers {'user-agent''my-app/0.0.1'}>>> requests.get(urlheaders=headers)

傳遞cookies

>>> requests.get(urlcookies=dict(cookies_are='working'))>>> r.text'{"cookies": {"cookies_are": "working"}}'

POST請求

傳遞表單

requests.post('http://httpbin.org/post'data {'key':'value'})

通常,你想要傳送一些編碼為表單形式的資料—非常像一個HTML表單。 要實現這個,只需簡單地傳遞一個字典給data引數。你的資料字典 在發出請求時會自動編碼為表單形式:

>>> payload {'key1''value1''key2''value2'}

>>> requests.post("http://httpbin.org/post"data=payload)>>> print(r.text){  ...  "form": {    "key2": "value2",    "key1": "value1"  },  ...}

很多時候你想要傳送的資料並非編碼為表單形式的。如果你傳遞一個string而不是一個dict,那麼資料會被直接釋出出去。

>>> requests.post(urldata=json.dumps(payload))

或者

>>> requests.post(urljson=payload)

傳遞檔案

url 'http://httpbin.org/post'>>> files {'file'open('report.xls''rb')}

>>> requests.post(urlfiles=files)

配置filesfilename, content_type and headers

files {'file': ('report.xls'open('report.xls''rb'), 'application/vnd.ms-excel', {'Expires''0'})}

files {'file': ('report.csv''some,data,to,send\nanother,row,to,send\n')}

響應

r.status_code

r.heards

r.cookies

跳轉

By default Requests will perform location redirection for all verbs except HEAD.

>>> requests.get('http://httpbin.org/cookies/set?k2=v2&k1=v1')

>>> r.status_code200

>>> r.history[<Response [302]>]

If you're using HEAD, you can enable redirection as well:

r=requests.head('http://httpbin.org/cookies/set?k2=v2&k1=v1',allow_redirects=True)

You can tell Requests to stop waiting for a response after a given number of seconds with the timeoutparameter:

requests.get('http://github.com'timeout=0.001)

高階特性

session,自動儲存cookies,可以設定請求引數,下次請求自動帶上請求引數

requests.Session()

s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')s