1. 程式人生 > >Python的requests軟體包詳解

Python的requests軟體包詳解

requests是一款Python的第三方HTTP類庫,便於進行HTTP訪問。
1. requests的特性

  • 能夠傳送HTTP 1.1請求
  • 無需手工為GET方法設定URL的請求引數,無需手工為POST方法組編碼表單形式
  • 藉助於urllib3實現HTTP請求的連線會話快取
  • 支援Python 2.6, 2.7, 3.3-3.7
2. requests的安裝

pip install requests

3. requests的介面
1) Main interfaces

  • requests.request()
  • requests.head()
  • requests.get('url', params={'key1':'value1', 'key2':'value2'},headers
    ={'user-agent': '...'}, cookies={'name1':'value2'})
  • requests.post('url', data={'key':'value'})
  • requests.post('url', json={'key':'value'})
  • requests.post('url', files={'uploaded_file': open('report.xls', 'rb')})
  • requests.post('url', files={'uploaded_file': ('report.xls', open('report.xls', 'rb'), 'application/excel', {'Expires': '0'})})
  • requests.post('url', files={'uploaded_file': ('temp.txt', 'one line\ntwo lines\n')})
  • requests.put('url', data={'key':'value'})
  • requests.patch()
  • requests.delete('url')
2) requests.Session類
import requests
requests.Session()

3) requests.Request類
import requests
requests.Request('GET', 'http://httpbin.org/get')

4) requests.PreparedRequest類
import requests
req = requests.Request('GET', 'http://httpbin.org/get')
preq = req.prepare()

5) requests.Response類
import requests
r = requests.get('https://api.github.com/events')
r.headers['content-type'] #'application/json;charset=utf8'
r.url
r.status_code #200==requests.codes.ok
r.encoding #'utf-8' by default
r.raw #raw content
r.text #text content
r.content #binary content
r.json()#json content, recommended
r.cookies['a_key']

注意:呼叫json()方法,如果返回結果不是有效的JSON資料,則丟擲ValueError異常。

6) requests.adapters.BaseAdapter類

7) requests.adapters.HTTPAdapter類

requests提供的使用urllib3的HTTP Adapter

參考連結:

官網,http://python-requests.org/

文件,http://docs.python-requests.org/en/master/

程式碼,https://github.com/requests/requests/

Release notes,http://docs.python-requests.org/en/master/community/updates/