雖然Python的標準庫中 urllib.request 模塊已經包含了日常咱們使用的大多數功能,可是它的 API 使用起來讓人感受不太好,而 Requests 自稱 「HTTP for Humans」,說明使用更簡潔方便。html
Requests 惟一的一個非轉基因的 Python HTTP 庫,人類能夠安全享用。python
Requests 繼承了urllib2的全部特性。Requests支持HTTP鏈接保持和鏈接池,支持使用cookie保持會話,支持文件上傳,支持自動肯定響應內容的編碼,支持國際化的 URL 和 POST 數據自動編碼。git
requests 的底層實現其實就是 urllib3。github
Requests的文檔很是完備,中文文檔也至關不錯。Requests能徹底知足當前網絡的需求,支持Python 2.6—3.6,並且能在PyPy下完美運行。web
Requests庫是Python中的一個HTTP請求第三方庫,用來簡化網絡請求,正則表達式
它有以下特徵,可以徹底知足如今的Web開發。json
1.Keep-Alive & 鏈接池。api
2.國際化域名和 URL。瀏覽器
3.帶持久 Cookie 的會話。安全
4.瀏覽器式的 SSL 認證。
5.自動內容解碼。
6.基本/摘要式的身份認證。
7.優雅的 key/value Cookie。
8.自動解壓。
9.Unicode 響應體。
10.HTTP(S) 代理支持。
11.文件分塊上傳。
12.流下載。
13.鏈接超時。
14.分塊請求。
15.支持 .netrc。
requests庫的安裝能夠經過pip install requests命令安裝或者利用easy_install均可以完成安裝,通常狀況都是經過pip install requests命令安裝。
使用 Requests發送網絡請求很是簡單。
第一步:須要導入 Requests 模塊:
import requests
第二步:建立一個Response對象,咱們能夠各類經過HTTP請求類型從這個對象中獲取全部咱們想要的信息。
例如:獲取 Github 的公共時間線。
Response = requests.get('https://api.github.com/events')
Response = requests.post('http://httpbin.org/post', data = {'key':'value'})
Response = requests.put('http://httpbin.org/put', data = {'key':'value'})
Response = requests.delete('http://httpbin.org/delete')
Response = requests.head('http://httpbin.org/get')
Response = requests.options('http://httpbin.org/get')
Get 、Post、PUT、DELETE、HEAD 以及 OPTIONS 都是requests 庫的HTTP請求類型,經常使用的通常是Get 、Post兩種,下面的教程也是以Get 、Post兩種爲主介紹相關的使用。
一般一個get完整的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)
print(r.url)
運行結果:
http://httpbin.org/get?key1=value1&key2=value2
注意字典裏值爲 None 的鍵都不會被添加到 URL 的查詢字符串裏。
例子:
import requests
payload = {'key1': 'value1', 'key2': None,'key3':'value3'}
r = requests.get("http://httpbin.org/get", params=payload)
print(r.url)
運行結果:
http://httpbin.org/get?key3=value3&key1=value1
你還能夠將一個列表做爲值傳入。
例子:
import requests
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get("http://httpbin.org/get", params=payload)
print(r.url)
運行結果:
http://httpbin.org/get?key2=value2&key2=value3&key1=value1
Get請求若是想添加 headers,能夠傳入headers參數來增長請求頭中的headers信息。若是要將參數放在url中傳遞,能夠利用 params 參數。
例子:
import requests
kw = {'wd':'電影'}
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
# params 接收一個字典或者字符串的查詢參數,字典類型自動轉換爲url編碼,不須要urlencode()
response = requests.get("http://www.baidu.com/s?", params = kw, headers = headers)
# 查看響應內容,response.text 返回的是Unicode格式的數據。
print(response.text)
# 查看響應內容,response.content返回的字節流數據。
print(response.content)
# 查看完整url地址。
print(response.url)
# 查看響應頭部字符編碼。
print(response.encoding)
# 查看響應碼。
print(response.status_code)
運行結果:
說明:
【response.text】:獲取響應內容。
【response.content】:也是獲取響應內容,可是返回的是字節流數據。
【response.url】:查看完整的請求URL。
【response.encoding】:查看響應頭部字符編碼。
【response.status_code】:查看響應狀態碼。
使用response.text 時,Requests 會基於 HTTP 響應的文本編碼自動解碼響應內容,大多數 Unicode 字符集都能被無縫地解碼。
使用response.content 時,返回的是服務器響應數據的原始二進制字節流,能夠用來保存圖片等二進制文件。
對於 POST 請求來講,咱們通常須要爲它增長一些參數。那麼最基本的傳參方法能夠利用 data 這個參數。
例子:
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
ret = requests.post("http://httpbin.org/post", data=payload)
print(ret.text)
運行結果:
{"args":{},"data":"","files":{},"form":{"key1":"value1","key2":"value2"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Content-Length":"23","Content-Type":"application/x-www-form-urlencoded","Host":"httpbin.org","User-Agent":"python-requests/2.18.4"},"json":null,"origin":"119.123.205.115","url":"http://httpbin.org/post"}
requests模塊的返回對象是一個Response對象,能夠從這個對象中獲取須要的信息。下面 r 表明Response對象。
【r.text】:文本響應內容。
【r.context】:二進制響應內容。
【r.json()】:JSON響應內容 。
【r.raw】:原始相應內容。
(1)文本響應內容。
例子:
import requests
r = requests.get('https://api.github.com/events')
print(r.text)
運行結果:
對於非文本請求,你也能以字節的方式訪問請求響應體。
(2)二進制響應內容。
對於非文本請求,你也能以字節的方式訪問請求響應體。
例子1:
import requests
r = requests.get('https://api.github.com/events')
print(r.content)
運行結果:
Requests 會自動爲你解碼 gzip 和 deflate 傳輸編碼的響應數據。
例子2,以請求返回的二進制數據建立一張圖片。
from PIL import Image
from io import BytesIO
i = Image.open(BytesIO(r.content))
(3)JSON響應內容。
Requests 中也有一個內置的 JSON 解碼器,助你處理 JSON 數據。
例子:
import requests
r = requests.get('https://github.com/timeline.json')
print(r.json())
運行結果:
若是 JSON 解碼失敗, r.json 就會拋出一個異常。例如,相應內容是 401 (Unauthorized),嘗試訪問 r.json 將會拋出 ValueError: No JSON object could be decoded 異常。
(4)Raw響應內容。
在罕見的狀況下,你可能想獲取來自服務器的原始套接字響應,那麼你能夠訪問 r.raw。 若是你確實想這麼幹,那請你確保在初始請求中設置了 stream=True。具體你能夠這麼作。
例子:
import requests
r = requests.get('https://github.com/timeline.json', stream=True)
print(r.raw)
運行結果:
但通常狀況下,你應該如下面的模式將文本流保存到文件。
with open(filename, 'wb') as fd:
for chunk in r.iter_content(chunk_size):
fd.write(chunk)
使用 Response.iter_content 將會處理大量你直接使用 Response.raw 不得不處理的。 當流下載時,上面是優先推薦的獲取內容方式。
Requests會自動將從Server返回的內容解碼。許多Unicode字符也會被解碼。
請求發出後,Requests 會基於 HTTP 頭部對響應的編碼做出有根據的推測。當你訪問 r.text 之時,Requests 會使用其推測的文本編碼。你能夠找出 Requests 使用了什麼編碼,而且可以使用r.encoding 屬性來改變它:
若是你改變了編碼,每當你訪問 r.text ,Request 都將會使用 r.encoding 的新值。你可能但願在使用特殊邏輯計算出文本的編碼的狀況下來修改編碼。好比 HTTP 和 XML 自身能夠指定編碼。這樣的話,你應該使用 r.content 來找到編碼,而後設置 r.encoding 爲相應的編碼。這樣就能使用正確的編碼解析 r.text 了。
在你須要的狀況下,Requests 也可使用定製的編碼。若是你建立了本身的編碼,並使用codecs 模塊進行註冊,你就能夠輕鬆地使用這個解碼器名稱做爲 r.encoding 的值, 而後由 Requests 來爲你處理編碼。
例子:
import requests
r = requests.get('https://api.github.com/events')
print(r.text)
print(r.encoding)
r.encoding = 'ISO-8859-1'
print(r.encoding)
運行結果:
若是你想爲請求添加 HTTP 頭部,只要簡單地傳遞一個 dict 給 headers 參數就能夠了。
例如,在前一個示例中咱們沒有指定 content-type。
import requests
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
注意: 定製 header 的優先級低於某些特定的信息源,例如:
1.若是在 .netrc 中設置了用戶認證信息,使用 headers= 設置的受權就不會生效。而若是設置了auth= 參數,.netrc 的設置就無效了。
2.若是被重定向到別的主機,受權 header 就會被刪除。
3.代理受權 header 會被 URL 中提供的代理身份覆蓋掉。
4.在咱們能判斷內容長度的狀況下,header 的 Content-Length 會被改寫。
更進一步講,Requests 不會基於定製 header 的具體狀況改變本身的行爲。只不過在最後的請求中,全部的 header 信息都會被傳遞進去。
注意: 全部的 header 值必須是 string、bytestring 或者 unicode。儘管傳遞 unicode header 也是容許的,但不建議這樣作。
咱們能夠經過r.status_code檢測響應狀態碼。
例子:
import requests
r = requests.get('http://httpbin.org/get')
print(r.status_code)
運行結果:
爲方便引用,Requests還附帶了一個內置的狀態碼查詢對象。
r.status_code == requests.codes.ok
若是發送了一個錯誤請求(一個 4XX 客戶端錯誤,或者 5XX 服務器錯誤響應),咱們能夠經過Response.raise_for_status() 來拋出異常。
import requests
r = requests.get('http://httpbin.org/get')
print(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() 時,獲得的是:None。
咱們能夠經過r.headers查看以一個請求的服務器響應頭。
例子:
import requests
r = requests.get('http://httpbin.org/get')
print(r.headers)
運行結果:
{'Server': 'gunicorn/19.8.1',
'Access-Control-Allow-Origin': '*',
'Content-Length': '211',
'Content-Type': 'application/json',
'Connection': 'keep-alive',
'Access-Control-Allow-Credentials': 'true',
'Date': 'Sun, 17 Jun 2018 03:21:54 GMT',
'Via': '1.1 vegur'}
返回的是一個字典,這個字典比較特殊:它是僅爲 HTTP 頭部而生的,HTTP 頭部是大小寫不敏感的,所以,咱們可使用任意大寫形式來編寫這些響應頭字段。
還有一個特殊點,那就是服務器能夠屢次接受同一 header,每次都使用不一樣的值。 Requests 會自動將它們合併。
咱們能夠經過r.cookies 去獲取一個請求的cookies,特別是在實戰中登陸模塊用的比較多,咱們能夠經過cookies進行登陸。
例子1:
import requests
response = requests.get("http://www.baidu.com/")
# 返回CookieJar對象:
cookiejar = response.cookies
# 將CookieJar轉爲字典:
cookiedict = requests.utils.dict_from_cookiejar(cookiejar)
print(cookiejar)
print(cookiedict)
運行結果:
例子2:利用Cookie模擬登陸步驟:
1.在瀏覽器輸入http://demo.bxcker.com,輸入用戶名和密碼登陸。
2.登陸成功點「客戶管理」模塊。
3.進入客戶管理模塊,顯示客戶列表。
4.經過抓包工具抓取客戶列表,獲得登陸後的Cookie信息。
GET http://demo.bxcker.com/customer/index.shtml HTTP/1.1
Host: demo.bxcker.com
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: */*
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36
Referer: http://demo.bxcker.com/
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Cookie: IEX-JSESSIONID=WFPlPUVbbbkQ76XPCr9tXRB4voK0eESo; Hm_lvt_4320d635415dcfd7831a11fa64aec173=1526347940; Hm_lpvt_4320d635415dcfd7831a11fa64aec173=1526347940; SPRING_SECURITY_REMEMBER_ME_COOKIE=UE9kSDFGMnVsS291S2Z2V1k5c1daQT09OjZxWFVDUUhoVmR2UTdsWnRFRnlZZ0E9PQ
5.利用sublime text工具處理抓到的http請求頭信息替換成字典。
選擇內容替換的方式是用正則表達式。
內容填寫:^(.*):\s(.*)$ (須要把header文件內容處理成字典,中間有個空格,因此加個\s)
替換爲填寫:"\1":"\2",
點全換,處理完成以後變成以下:
"Host":"demo.bxcker.com",
"Connection":"keep-alive",
"Pragma":"no-cache",
"Cache-Control":"no-cache",
"Accept":"*/*",
"X-Requested-With":"XMLHttpRequest",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
"Referer":"http://demo.bxcker.com/",
"Accept-Encoding":"gzip, deflate",
"Accept-Language":"zh-CN,zh;q=0.9",
"Cookie":"IEX-JSESSIONID=WFPlPUVbbbkQ76XPCr9tXRB4voK0eESo; Hm_lvt_4320d635415dcfd7831a11fa64aec173=1526347940; Hm_lpvt_4320d635415dcfd7831a11fa64aec173=1526347940; SPRING_SECURITY_REMEMBER_ME_COOKIE=UE9kSDFGMnVsS291S2Z2V1k5c1daQT09OjZxWFVDUUhoVmR2UTdsWnRFRnlZZ0E9PQ",
6. 處理完成以後直接拷貝到Python定義的頭信息變量headers={}裏。
7. 整理headers 信息(去掉一些沒用的,保留一些重要的)。
"Connection":"keep-alive",
"X-Requested-With":"XMLHttpRequest",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
"Referer":"http://demo.bxcker.com/",
"Cookie":"IEX-JSESSIONID=WFPlPUVbbbkQ76XPCr9tXRB4voK0eESo; Hm_lvt_4320d635415dcfd7831a11fa64aec173=1526347940; Hm_lpvt_4320d635415dcfd7831a11fa64aec173=1526347940; SPRING_SECURITY_REMEMBER_ME_COOKIE=UE9kSDFGMnVsS291S2Z2V1k5c1daQT09OjZxWFVDUUhoVmR2UTdsWnRFRnlZZ0E9PQ",
8. 編寫完整的程序。
import requests
from urllib import parse
url ="http://demo.bxcker.com/qhiex_login"
headers ={
"Referer": "http://demo.bxcker.com/",
"Connection": "keep-alive",
"X-Requested-With": "XMLHttpRequest",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded",
"Accept-Language": "zh-CN,zh;q=0.9",
}
data ={"username":"demo100","password":"demo100"}
# 經過urlencode()轉碼
postdata = parse.urlencode(data).encode(encoding='UTF8')
response = requests.post(url, data = postdata,headers=headers)
# 返回CookieJar對象:
cookiejar = response.cookies
# 將CookieJar轉爲字典:
cookiedict = requests.utils.dict_from_cookiejar(cookiejar)
print(cookiejar)
print(cookiedict)
#利用cookie登陸,訪問客戶管理模塊
r=requests.get("http://demo.bxcker.com/customer/index.shtml",headers=headers)
# 響應內容轉碼
r.encoding = 'utf-8'
#打印響應內容
print(r.text)
運行結果:
能夠看到客戶列表裏的相關信息,證實是經過Cookie登陸成功,而後跳轉到客戶管理模塊,獲取的客戶信息。
在 requests 裏,session對象是一個很是經常使用的對象,這個對象表明一次用戶會話:從客戶端瀏覽器鏈接服務器開始,到客戶端瀏覽器與服務器斷開。
會話能讓咱們在跨請求時候保持某些參數,好比在同一個 Session 實例發出的全部請求之間保持 cookie 。
例子:利用Sission實現登陸。
import requests
from urllib import parse
url ="http://demo.bxcker.com/qhiex_login"
headers ={
"Referer": "http://demo.bxcker.com/",
"Connection": "keep-alive",
"X-Requested-With": "XMLHttpRequest",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded",
"Accept-Language": "zh-CN,zh;q=0.9",
}
data ={"username":"demo100","password":"demo100"}
# 建立session對象,能夠保存Cookie值。
ssion = requests.session()
# 發送附帶用戶名和密碼的請求,並獲取登陸後的Cookie值,保存在ssion裏。
ssion.post("http://www.renren.com/PLogin.do", data = data)
# ssion包含用戶登陸後的Cookie值,能夠直接訪問那些登陸後才能夠訪問的頁面。
r = ssion.get("http://demo.bxcker.com/customer/index.shtml",headers=headers)
# 響應內容轉碼。
r.encoding = 'utf-8'
# 打印響應內容。
print(r.text)
運行結果:
默認狀況下,除了 HEAD, Requests 會自動處理全部重定向。
可使用響應對象的 history 方法來追蹤重定向。
Response.history 是一個 Response 對象的列表,爲了完成請求而建立了這些對象。這個對象列表按照從最老到最近的請求進行排序。
例如:Github 將全部的 HTTP 請求重定向到 HTTPS。
import requests
r = requests.get('http://github.com')
print(r.url)
#'https://github.com/'
print(r.status_code)
# 200
print(r.history)
#[<Response [301]>]
若是你使用的是GET、OPTIONS、POST、PUT、PATCH 或者 DELETE,那麼你能夠經過 allow_redirects 參數禁用重定向處理:
import requests
r = requests.get('http://github.com',allow_redirects=False)
print(r.status_code)
# 301
print(r.history)
#[]
若是你使用了 HEAD,你也能夠啓用重定向:
例子:
import requests
r = requests.get('http://github.com',allow_redirects=False)
print(r.url)
#'https://github.com/'
print(r.history)
#[<Response [301]>]
你能夠告訴 requests 在通過以 timeout 參數設定的秒數時間以後中止等待響應。
requests.get('http://github.com', timeout=0.001)
若是須要使用代理,你能夠經過爲任意請求方法提供 proxies 參數來配置單個請求。
例子:
import requests
# 根據協議類型,選擇不一樣的代理
proxies = {
"http": "http://12.34.56.79:9527",
"https": "http://12.34.56.79:9527",
}
response = requests.get("http://www.baidu.com", proxies = proxies)
print response.text
也能夠經過本地環境變量 HTTP_PROXY 和 HTTPS_PROXY 來配置代理:
export HTTP_PROXY="http://12.34.56.79:9527"
export HTTPS_PROXY="https://12.34.56.79:9527"
urllib.request庫 的作法比較複雜,requests只須要一步。
1.私密代理。
例子:
import requests
# 若是代理須要使用HTTP Basic Auth,可使用下面這種格式:
proxy = { "http": "xny_123:abc123@61.158.163.130:16816" }
response = requests.get("http://www.baidu.com", proxies = proxy)
print(response.text)
2.web客戶端驗證。
若是是Web客戶端驗證,須要添加 auth = (帳戶名, 密碼)。
例子:
import requests
auth=('xiaony', 'xny123')
response = requests.get('http://192.168.1.102', auth = auth)
print(response.text)
Requests也能夠爲HTTPS請求驗證SSL證書。
要想檢查某個主機的SSL證書,你可使用 verify 參數(也能夠不寫)。
例子:
import requests
r = requests.get("https://www.baidu.com/", verify=True)
# 也能夠省略不寫
# r = requests.get("https://www.baidu.com/")
print(r.encoding)
# 響應轉碼
r.encoding = 'utf-8'
print(r.text)
運行結果: