python-requests快速上手

網址地址:http://cn.python-requests.org/zh_CN/latest/user/quickstart.htmlhtml

requests的安裝略過python

發送請求

使用Requests發送網絡請求很是簡單。nginx

一開始要導入Requests模塊:git

>>> import requests

而後,嘗試獲取某個網頁。本例子中,咱們來獲取Github的公共時間線github

>>> r = requests.get('https://github.com/timeline.json')

如今,咱們有一個名爲 r 的 Response 對象。能夠從這個對象中獲取全部咱們想要的信息。json

Requests簡便的API意味着全部HTTP請求類型都是顯而易見的。例如,你能夠這樣發送一個HTTP POST請求:api

>>> r = requests.post("http://httpbin.org/post")

漂亮,對吧?那麼其餘HTTP請求類型:PUT, DELETE, HEAD以及OPTIONS又是如何的呢?都是同樣的簡單:服務器

>>> r = requests.put("http://httpbin.org/put")
>>> r = requests.delete("http://httpbin.org/delete")
>>> r = requests.head("http://httpbin.org/get")
>>> r = requests.options("http://httpbin.org/get")

都很不錯吧,但這也僅是Requests的冰山一角呢。cookie

爲URL傳遞參數

你也許常常想爲URL的查詢字符串(query string)傳遞某種數據。若是你是手工構建URL,那麼數據會以鍵/值 對的形式置於URL中,跟在一個問號的後面。例如,httpbin.org/get?key=val 。 Requests容許你使用 params 關鍵字參數,以一個字典來提供這些參數。舉例來講,若是你想傳遞 key1=value1 和 key2=value2 到 httpbin.org/get,那麼你可使用以下代碼:網絡

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get("http://httpbin.org/get", params=payload)

經過打印輸出該URL,你能看到URL已被正確編碼:

>>> print(r.url)
http://httpbin.org/get?key2=value2&key1=value1

注意字典裏值爲 None 的鍵都不會被添加到 URL 的查詢字符串裏。

響應內容

咱們能讀取服務器響應的內容。再次以Github時間線爲例:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.text
u'[{"repository":{"open_issues":0,"url":"https://github.com/...

Requests會自動解碼來自服務器的內容。大多數unicode字符集都能被無縫地解碼。

請求發出後,Requests會基於HTTP頭部對響應的編碼做出有根據的推測。當你訪問r.text 之時,Requests會使用其推測的文本編碼。你能夠找出Requests使用了什麼編碼,而且可以使用 r.encoding 屬性來改變它:

>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'

若是你改變了編碼,每當你訪問 r.text ,Request都將會使用 r.encoding 的新值。你可能但願在使用特殊邏輯計算出文本的編碼的狀況下來修改編碼。好比 HTTP 和 XML 自身能夠指定編碼。這樣的話,你應該使用 r.content 來找到編碼,而後設置 r.encoding爲相應的編碼。這樣就能使用正確的編碼解析 r.text 了。

在你須要的狀況下,Requests也可使用定製的編碼。若是你建立了本身的編碼,並使用codecs 模塊進行註冊,你就能夠輕鬆地使用這個解碼器名稱做爲 r.encoding 的值, 而後由Requests來爲你處理編碼。

二進制響應內容

你也能以字節的方式訪問請求響應體,對於非文本請求:

>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...

Requests會自動爲你解碼 gzip 和 deflate 傳輸編碼的響應數據。

例如,以請求返回的二進制數據建立一張圖片,你可使用以下代碼:

>>> from PIL import Image
>>> from StringIO import StringIO
>>> i = Image.open(StringIO(r.content))

JSON響應內容

Requests中也有一個內置的JSON解碼器,助你處理JSON數據:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

若是JSON解碼失敗, r.json 就會拋出一個異常。例如,相應內容是 401 (Unauthorized) ,嘗試訪問 r.json 將會拋出 ValueError: No JSON object could be decoded 異常。

原始響應內容

在罕見的狀況下你可能想獲取來自服務器的原始套接字響應,那麼你能夠訪問 r.raw 。 若是你確實想這麼幹,那請你確保在初始請求中設置了 stream=True 。具體的你能夠這麼作:

>>> r = requests.get('https://github.com/timeline.json', 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'

但通常狀況下,你應該下面的模式將文本流保存到文件:

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

使用 Response.iter_content 將會處理大量你直接使用 Response.raw 不得不處理的。 當流下載時,上面是優先推薦的獲取內容方式。

定製請求頭

若是你想爲請求添加HTTP頭部,只要簡單地傳遞一個 dict 給 headers 參數就能夠了。

例如,在前一個示例中咱們沒有指定content-type:

>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json'}

>>> r = requests.post(url, data=json.dumps(payload), headers=headers)

更加複雜的POST請求

一般,你想要發送一些編碼爲表單形式的數據—很是像一個HTML表單。 要實現這個,只需簡單地傳遞一個字典給 data 參數。你的數據字典 在發出請求時會自動編碼爲表單形式:

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

不少時候你想要發送的數據並不是編碼爲表單形式的。若是你傳遞一個 string 而不是一個dict ,那麼數據會被直接發佈出去。

例如,Github API v3接受編碼爲JSON的POST/PATCH數據:

>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}

>>> r = requests.post(url, data=json.dumps(payload))

POST一個多部分編碼(Multipart-Encoded)的文件

Requests使得上傳多部分編碼文件變得很簡單:

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

>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "<censored...binary...data>"
  },
  ...
}

你能夠顯式地設置文件名,文件類型和請求頭:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}

>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "<censored...binary...data>"
  },
  ...
}

若是你想,你也能夠發送做爲文件來接收的字符串:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}

>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "some,data,to,send\\nanother,row,to,send\\n"
  },
  ...
}

若是你發送一個很是大的文件做爲 multipart/form-data 請求,你可能但願流請求(?)。默認下 requests 不支持, 但有個第三方包支持 - requests-toolbelt. 你能夠閱讀 toolbelt 文檔 來了解使用方法。

在一個請求中發送多文件參考 高級用法 一節.

響應狀態碼

咱們能夠檢測響應狀態碼:

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

爲方便引用,Requests還附帶了一個內置的狀態碼查詢對象:

>>> r.status_code == requests.codes.ok
True

若是發送了一個失敗請求(非200響應),咱們能夠經過 Response.raise_for_status() 來拋出異常:

>>> bad_r = requests.get('http://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

可是,因爲咱們的例子中 r 的 status_code 是 200 ,當咱們調用 raise_for_status()時,獲得的是:

>>> r.raise_for_status()
None

一切都挺和諧哈。

響應頭

咱們能夠查看以一個Python字典形式展現的服務器響應頭:

>>> r.headers
{
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json'
}

可是這個字典比較特殊:它是僅爲HTTP頭部而生的。根據 RFC 2616 , HTTP頭部是大小寫不敏感的。

所以,咱們可使用任意大寫形式來訪問這些響應頭字段:

>>> r.headers['Content-Type']
'application/json'

>>> r.headers.get('content-type')
'application/json'

Cookies

若是某個響應中包含一些Cookie,你能夠快速訪問它們:

>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)

>>> r.cookies['example_cookie_name']
'example_cookie_value'

要想發送你的cookies到服務器,可使用 cookies 參數:

>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')

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

重定向與請求歷史

默認狀況下,除了 HEAD, Requests會自動處理全部重定向。

可使用響應對象的 history 方法來追蹤重定向。

Response.history 是一個:class:Response <requests.Response> 對象的列表,爲了完成請求而建立了這些對象。這個對象列表按照從最老到最近的請求進行排序。

例如,Github將全部的HTTP請求重定向到HTTPS。:

>>> r = requests.get('http://github.com')
>>> r.url
'https://github.com/'
>>> r.status_code
200
>>> r.history
[<Response [301]>]

若是你使用的是GET, OPTIONS, POST, PUT, PATCH 或者 DELETE,,那麼你能夠經過allow_redirects 參數禁用重定向處理:

>>> r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]

若是你使用的是HEAD,你也能夠啓用重定向:

>>> r = requests.head('http://github.com', allow_redirects=True)
>>> r.url
'https://github.com/'
>>> r.history
[<Response [301]>]

超時

你能夠告訴requests在通過以 timeout 參數設定的秒數時間以後中止等待響應:

>>> requests.get('http://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)

注:

timeout 僅對鏈接過程有效,與響應體的下載無關。 timeout is not a time limit on the entire response download; rather, an exception is raised if the server has not issued a response for timeout seconds (more precisely, if no bytes have been received on the underlying socket for timeout seconds).

錯誤與異常

遇到網絡問題(如:DNS查詢失敗、拒絕鏈接等)時,Requests會拋出一個ConnectionError 異常。

遇到罕見的無效HTTP響應時,Requests則會拋出一個 HTTPError 異常。

若請求超時,則拋出一個 Timeout 異常。

若請求超過了設定的最大重定向次數,則會拋出一個 TooManyRedirects 異常。

全部Requests顯式拋出的異常都繼承自 requests.exceptions.RequestException 。

相關文章
相關標籤/搜索