Requests 是使用 Apache2 Licensed 許可證的 HTTP 庫。用 Python 編寫,真正的爲人類着想。html
Python 標準庫中的 urllib2 模塊提供了你所須要的大多數 HTTP 功能,可是它的 API 太渣了。它是爲另外一個時代、另外一個互聯網所建立的。它須要巨量的工做,甚至包括各類方法覆蓋,來完成最簡單的任務。python
總之,你們之後對urllib2庫敬而遠之就好了。來擁抱Requests吧。nginx
Requests的官方文檔:http://cn.python-requests.org/zh_CN/latest/git
經過下面方法安裝requestsgithub
pip install requests
很是簡單,先導入requests,apache
import requests
而後,按照下面的方法發送http的各類請求:json
r = requests.get('https://github.com/timeline.json') 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("http://httpbin.org/get")
若是http請求須要帶URL參數(注意是URL參數不是body參數),那麼須要將參數附帶到payload字典裏頭,按照下面的方法發送請求:flask
import requests payload = {'key1': 'value1', 'key2': 'value2'} r = requests.get("http://httpbin.org/get",params=payload) print r.url
經過print(r.url)能看到URL已被正確編碼:服務器
http://httpbin.org/get?key2=value2&key1=value1
注意字典裏值爲 None 的鍵都不會被添加到 URL 的查詢字符串裏。cookie
import requests r = requests.get('https://github.com/timeline.json') r.text
響應結果是:
{"message":"Hello there, wayfaring stranger. If you're reading this then you probably didn't see our blog post a couple of years back announcing that this API would Go away: http://Git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.","documentation_url":"https://developer.github.com/v3/activity/events/#list-public-events"}
Requests會自動解碼來自服務器的內容。大多數unicode字符集都能被無縫地解碼。請求發出後,Requests會基於HTTP頭部對響應的編碼做出有根據的推測。當你訪問r.text之時,Requests會使用其推測的文本編碼。你能夠找出Requests使用了什麼編碼,而且可以使用r.encoding 屬性來改變它
>>> r.encoding 'utf-8'
若是請求返回的是二進制的圖片,你可使用r.content訪問請求響應體。
import requests from PIL import Image from StringIO import StringIO r = requests.get('http://cn.python-requests.org/zh_CN/latest/_static/requests-sidebar.png') i = Image.open(StringIO(r.content)) i.show()
Requests中也有一個內置的JSON解碼器,助你處理JSON數據:
import requests r = requests.get('https://github.com/timeline.json') print r.json()
r.json將返回的json格式字符串解碼成python字典。r.text返回的utf-8的文本。
若是你想爲請求添加HTTP頭部,只要簡單地傳遞一個 dict 給headers 參數就能夠了。
import requests import json payload = {'some': 'data'} headers = {'content-type': 'application/json'} r = requests.get('https://github.com/timeline.json', data=json.dumps(payload), headers=headers) print r.json()
注意,這裏的payload是放到body裏面的,因此params參數要使用json數據。
就像上面‘定製請求頭’中的例子,將payload序列化爲json格式數據,傳遞給data參數。
先製做一個text文件,名爲‘report.txt’,內容是‘this is a file’。Requests使得上傳多部分編碼文件變得很簡單:
import requests url = 'http://httpbin.org/post' files = {'file': open('report.txt', 'rb')} r = requests.post(url, files=files) print r.text
返回結果是:
C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/flaskexample/postfile.py { "args": {}, "data": "", "files": { <strong>"file": "this is a file"</strong> }, "form": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "160", "Content-Type": "multipart/form-data; boundary=a3b41a6300214ffdb55ddbc23dfc0d91", "Host": "httpbin.org", "User-Agent": "python-requests/2.7.0 CPython/2.7.9 Windows/2012Server" }, "json": null, "origin": "202.108.92.226", "url": "http://httpbin.org/post" } Process finished with exit code 0
傳遞一個字典給 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.6.0 CPython/2.7.10 Windows/7" }, "json": null, "origin": "124.251.251.2", "url": "http://httpbin.org/post" }
使用r.status_code返回響應的狀態碼。
import requests r = requests.get('http://httpbin.org/get') print r.status_code
爲方便引用,Requests還附帶了一個內置的狀態碼查詢對象:
print r.status_code == requests.codes.ok
若是發送了一個失敗請求(非200響應),咱們能夠經過 Response.raise_for_status()來拋出異常:
import requests bad_r = requests.get('http://httpbin.org/status/404') print bad_r.status_code bad_r.raise_for_status()
返回結果是:
C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/flaskexample/postfile.py 404 Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/flaskexample/postfile.py", line 5, in <module> bad_r.raise_for_status() File "C:\Python27\lib\site-packages\requests\models.py", line 851, in raise_for_status raise HTTPError(http_error_msg, response=self) <strong>requests.exceptions.HTTPError: 404 Client Error: NOT FOUND</strong> Process finished with exit code 1
若是返回碼是200,則不會拋出異常,即:
import requests bad_r = requests.get('http://httpbin.org/get') print bad_r.status_code bad_r.raise_for_status()
的返回結果是:
C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/flaskexample/postfile.py 200 Process finished with exit code 0
咱們能夠查看以一個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' }
讀取某一個頭部字段:
r.headers['Content-Type'] r.headers.get('content-type')
獲得響應中包含的一些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
返回結果:
u'{\n "cookies": {\n "cookies_are": "working"\n }\n}\n'
默認狀況下,除了 HEAD, Requests會自動處理全部重定向。
可使用響應對象的 history
方法來追蹤重定向。
>>> 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]>]