學習Requests-快速上手

http://cn.python-requests.org/zh_CN/latest/user/quickstart.html 快速上手html

學習文檔並記錄下過程,但願本身能理解更多的知識python

開始時導入模塊:nginx

>>> import requests

發送請求

試着獲取網頁的內容:git

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

注:https的網址會須要去驗證證書,如上網址返回:/Library/Python/2.7/site-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarninggithub

>>> print r
<Response [410]>

能夠看出如今咱們獲得了一個名叫r的 Respons 對象。從這個對象中咱們能夠獲取想要的信息。json

Requsts簡便的API意味着全部的HTTP請求類型都是顯而易見的。例如以下些的POST、PUT、DELETE、HEAD、以及OPTION的請求類型:api

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


爲URL傳遞參數

人工建立URL時候數據會以 鍵/值 對的形式置於URL中,跟在一個問號後面。例如:httpbin.org/get?key=val服務器

Requests容許你使用params關鍵字參數,以一個字典來提供這些參數。舉例來講,若是你想傳遞key1=value1key2=value2httpbin.org/get ,那麼你可使用以下代碼:cookie

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

輸出的url能夠看出URL已經被正確編碼。注:payload中字典的值爲None時,該鍵不會被添加到URL的查詢字符中。網絡


響應內容

>>> r = requests.get('http://httpbin.org/get')
>>> r.text
u'{\n  "args": {}, \n  "headers": {\n    "Accept": "*/*", \n    "Accept-Encoding": "gzip, deflate", \n    "Host": "httpbin.org", \n    "User-Agent": "python-requests/2.7.0 CPython/2.7.6 Darwin/14.1.0"\n  }, \n  "origin": "202.134.124.242", \n  "url": "http://httpbin.org/get"\n}\n'

咱們會讀取服務器響應的內容。如上所示。Requests會自動解碼來自服務器的內容。大多數unicode字符集都能被無縫的解碼。

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

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

每次訪問r.text的時候,Requests都將會使用r.encoding的新值。


二進制響應內容

這個例子沒有成功完成,暫時跳過。


JSON響應內容

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

>>> r = requests.get('http://data.btcchina.com/data/ticker')
>>> r.json()
{u'ticker': {u'sell': u'1533.41', u'buy': u'1533.27', u'last': u'1533.41', u'vol': u'19893.28110000', u'prev_close': u'1527.52', u'vwap': u'1532.61', u'high': u'1558.68', u'low': u'1519.75', u'date': 1441609063, u'open': u'1527.52'}}

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


原始響應內容(極少用到)

>>> r = requests.get('https://github.com/timeline.json', stream=True)
>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x10a153610>
>>> r.raw.read
<bound method HTTPResponse.read of <requests.packages.urllib3.response.HTTPResponse object at 0x10a153610>>
>>> r.raw.read()
''


定製請求頭

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

>>> 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
{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "key1": "value1",
    "key2": "value2"
  },
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Content-Length": "23",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.7.0 CPython/2.7.6 Darwin/14.1.0"
  },
  "json": null,
  "origin": "202.134.124.242",
  "url": "http://httpbin.org/post"
}


響應頭

>>> r.headers
{'content-length': '449', 'server': 'nginx', 'connection': 'keep-alive', 
'access-control-allow-credentials': 'true', 'date': 'Mon, 07 Sep 2015 07:54:13 GMT', 
'access-control-allow-origin': '*', 'content-type': 'application/json'}

HTTP頭部是大小寫不敏感的。所以,咱們可使用任意大寫形式來訪問這些響應頭字段:

>>> r.headers.get('content-type')
'application/json'
>>> r.headers['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會自動處理全部重定向。

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

>>> type(r.history)
<type 'list'>
>>> type(r)
<class 'requests.models.Response'>

能夠看出,Response.history是一個列表,爲了完成請求而建立了這些對象。這個對象列表按照時間由遠到近的請求進行排序。例如:

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

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

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

若是你使用的是HEAD,你也能夠啓用重定向,設置allow_redirects=True.


超時

你能夠告訴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 僅對鏈接過程有效,與響應體的下載無關。

錯誤與異常

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

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

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

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

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

相關文章
相關標籤/搜索