PS:文章摘自下面這位大神的鏈接。
作者:AlexMercer313
鏈接:http://www.lxweimin.com/p/d662205283a4
來源:簡書
Requests是用Python語言編寫,基于urllib,采用Apache2 Licensed開源協議的HTTP庫。它比urllib更加方便,可以節約我們大量的工作,完全滿足HTTP測試需求。Requests的哲學是以PEP 20的習語為中心開發的,所以它比urllib更加Pythoner。更重要的一點是它支持Python3哦!
Beautiful is better than ugly.(美麗優于丑陋)
Explicit is better than implicit.(清楚優于含糊)
Simple is better than complex.(簡單優于復雜)
Complex is better than complicated.(復雜優于繁瑣)
Readability counts.(重要的是可讀性)
一、安裝request
通過pip安裝
pip install requests
或者,下載代碼后安裝:
$ git clone git://github.com/kennethreitz/requests.git$ cd requests
$ python setup.pyinstall
再懶一點,通過IDE安裝吧,如pycharm!
二、發送請求與傳遞參數
先來一個簡單的例子吧!讓你了解下其威力:
importre quests
r= requests.get(url='http://www.itwhy.org')#最基本的GET請求
print(r.status_code)#獲取返回狀態
r = requests.get(url='http://dict.baidu.com/s',params={'wd':'python'})#帶參數的GET請求
print(r.url)
print(r.text)#打印解碼后的返回數據
很簡單吧!不但GET方法簡單,其他方法都是統一的接口樣式哦!
requests.get(‘https://github.com/timeline.json’)#GET請求
requests.post(“http://httpbin.org/post”)#POST請求
requests.put(“http://httpbin.org/put”)#PUT請求
requests.delete(“http://httpbin.org/delete”)#DELETE請求
requests.head(“http://httpbin.org/get”)#HEAD請求
requests.options(“http://httpbin.org/get”)#OPTIONS請求
PS:以上的HTTP方法,對于WEB系統一般只支持 GET 和 POST,有一些還支持 HEAD 方法。
帶參數的請求實例:
import requests
requests.get('http://www.dict.baidu.com/s',params={'wd':'python'})#GET參數實例requests.post('http://www.itwhy.org/wp-comments-post.php',data={'comment':'測試POST'})#POST參數實例
POST發送JSON數據:
import requests?
import json
r= requests.post('https://api.github.com/some/endpoint',data=json.dumps({'some':'data'}))print(r.json())
定制header:
import requests?
importjson
data= {'some':'data'}
headers= {'content-type':'application/json','User-Agent':'Mozilla/5.0(X11;Ubuntu;Linux x86_64;rv:22.0)Gecko/20100101 Firefox/22.0'}
r= requests.post('https://api.github.com/some/endpoint',data=data,headers=headers)print(r.text)
三、response對象
使用requests方法后,會返回一個response對象,其存儲了服務器響應的內容,如上實例中已經提到的r.text、r.status_code……
獲取文本方式的響應體實例:當你訪問 r.text 之時,會使用其響應的文本編碼進行解碼,并且你可以修改其編碼讓 r.text 使用自定義的編碼進行解碼。
r = requests.get('http://www.itwhy.org')print(r.text,'\n{}\n'.format('*'*79),r.encoding)
r.encoding='GBK'print(r.text,'\n{}\n'.format('*'*79),r.encoding)
其他響應:
r.status_code #響應狀態碼
r.raw #返回原始響應體,也就是urllib的response對象,使用r.raw.read()讀取
r.content #字節方式的響應體,會自動為你解碼gzip和deflate壓縮
r.text #字符串方式的響應體,會自動根據響應頭部的字符編碼進行解碼
r.headers #以字典對象存儲服務器響應頭,但是這個字典比較特殊,字典鍵不區分大小寫,若鍵不存在則返回None
#*特殊方法*#
r.json()#Requests中內置的JSON解碼器
r.raise_for_status()#失敗請求(非200響應)拋出異常
案例之一:
importrequests
URL='http://ip.taobao.com/service/getIpInfo.php'#淘寶IP地址庫APItry:
r= requests.get(URL,params={'ip':'8.8.8.8'},timeout=1)
r.raise_for_status()#如果響應狀態碼不是200,就主動拋出異常exceptrequests.RequestException as e:print(e)else:
result=r.json()print(type(result),result,sep='\n')
四、上傳文件
使用 Requests 模塊,上傳文件也是如此簡單的,文件的類型會自動進行處理:
importrequests
url='http://127.0.0.1:5000/upload'
files= {'file': open('/home/lyb/sjzl.mpg','rb')
}#files = {'file':('report.jpg',open('/home/lyb/sjzl.mpg','rb'))}? ? #顯式的設置文件名
r= requests.post(url,files=files)print(r.text)
更加方便的是,你可以把字符串當著文件進行上傳:
importrequests
url='http://127.0.0.1:5000/upload'
files= {'file':('test.txt',b'Hello Requests.')}#必需顯式的設置文件名
r= requests.post(url,files=files)print(r.text)
五、身份驗證
基本身份認證(HTTP Basic Auth):
import requests
from requests.auth import HTTPBasicAuth
r= requests.get('https://httpbin.org/hidden-basic-auth/user/passwd',auth=HTTPBasicAuth('user','passwd'))
#r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd',auth=('user','passwd'))#簡寫print(r.json())
另一種非常流行的HTTP身份認證形式是摘要式身份認證,Requests對它的支持也是開箱即可用的:
requests.get(URL,auth=HTTPDigestAuth('user','pass'))
六、Cookies與會話對象
如果某個響應中包含一些Cookie,你可以快速訪問它們:
import requests
r= requests.get('http://www.google.com.hk/')
print(r.cookies['NID'])
print(tuple(r.cookies))
要想發送你的cookies到服務器,可以使用 cookies 參數:
import requests
url='http://httpbin.org/cookies'cookies= {'testCookies_1':'Hello_Python3','testCookies_2':'Hello_Requests'}#在Cookie Version 0中規定空格、方括號、圓括號、等于號、逗號、雙引號、斜杠、問號、@,冒號,分號等特殊符號都不能作為Cookie的內容。
r = requests.get(url,cookies=cookies)
print(r.json())
會話對象讓你能夠跨請求保持某些參數,最方便的是在同一個Session實例發出的所有請求之間保持cookies,且這些都是自動處理的,甚是方便。
下面就來一個真正的實例,如下是快盤簽到腳本:
import requests
headers= {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','Accept-Encoding':'gzip,deflate,compress','Accept-Language':'en-us;q=0.5,en;q=0.3','Cache-Control':'max-age=0','Connection':'keep-alive','User-Agent':'Mozilla/5.0(X11;Ubuntu;Linux x86_64;rv:22.0)Gecko/20100101 Firefox/22.0'}
s=requests.Session()
s.headers.update(headers)#s.auth =('superuser','123')
s.get('https://www.kuaipan.cn/account_login.htm')
_URL='http://www.kuaipan.cn/index.php's.post(_URL,params={'ac':'account','op':'login'},
data={'username':'****@foxmail.com','userpwd':'********','isajax':'yes'})
r= s.get(_URL,params={'ac':'zone','op':'taskdetail'})print(r.json())
s.get(_URL,params={'ac':'common','op':'usersign'})
七、超時與異常
timeout 僅對連接過程有效,與響應體的下載無關。
>>> requests.get('http://github.com',timeout=0.001)
Traceback(most recent call last):
File"",line 1,inrequests.exceptions.Timeout: HTTPConnectionPool(host='github.com',port=80): Request timed out.(timeout=0.001)
所有Requests顯式拋出的異常都繼承自requests.exceptions.RequestException:ConnectionError、HTTPError、Timeout、TooManyRedirects。
requests是python的一個HTTP客戶端庫,跟urllib,urllib2類似,那為什么要用requests而不用urllib2呢?官方文檔中是這樣說明的:
python的標準庫urllib2提供了大部分需要的HTTP功能,但是API太逆天了,一個簡單的功能就需要一大堆代碼。
插播個好消息!剛看到requests有了中文翻譯版,建議英文不好的看看,內容也比我的博客好多了,具體鏈接是:http://cn.python-requests.org/en/latest/。
1.安裝
當然,有easy_install或pip的朋友可以直接使用:easy_install requests或者pip install requests來安裝。
測試:在IDLE中輸入import requests,如果沒提示錯誤,那說明已經安裝成功了!
2.小試牛刀
>>>importrequests>>>r=requests.get('http://www.zhidaow.com')#發送請求>>>r.status_code#返回碼200>>>r.headers['content-type']#返回頭部信息'text/html;charset=utf8'>>>r.encoding#編碼信息'utf-8'>>>r.text#內容部分(PS,由于編碼問題,建議這里使用r.content)u'\n
是不是很簡單?比urllib2和urllib簡單直觀的多?!那請接著看快速指南吧。
3. 快速指南
3.1發送請求
發送請求很簡單的,首先要導入requests模塊:
>>>import requests
接下來讓我們獲取一個網頁,例如百度首頁:
>>>r=requests.get('http://www.baidu.com')
接下來,我們就可以使用這個r的各種方法和函數了。
另外,HTTP請求還有很多類型,比如POST,PUT,DELETE,HEAD,OPTIONS。也都可以用同樣的方式實現:
>>>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")
因為目前我還沒用到這些,所以沒有深入研究。
3.2在URLs中傳遞參數
有時候我們需要在URL中傳遞參數,比如在采集百度搜索結果時,我們wd參數(搜索詞)和rn參數(搜素結果數量),你可以手工組成URL,或者使用:
r=requests.get(“http://www.baidu.com/”,params={“wd”:”test”})。
3.3 獲取響應內容
可以通過r.text來獲取網頁的內容。
>>>r=requests.get('https://www.zhidaow.com')>>>r.textu'\n
文檔里說,requests會自動將內容轉碼。大多數unicode字體都會無縫轉碼。但我在cygwin下使用時老是出現UnicodeEncodeError錯誤,郁悶。倒是在python的IDLE中完全正常。
另外,還可以通過r.content來獲取頁面內容。
>>>r=requests.get('https://www.zhidaow.com')>>>r.contentb'\n
文檔中說r.content是以字節的方式去顯示,所以在IDLE中以b開頭。但我在cygwin中用起來并沒有,下載網頁正好。所以就替代了urllib2的urllib2.urlopen(url).read()功能。(基本上是我用的最多的一個功能。)
3.4 獲取網頁編碼
可以使用r.encoding來獲取網頁編碼。
>>>r=requests.get('http://www.baidu.com')>>>r.encoding'utf-8'
當你發送請求時,requests會根據HTTP頭部來猜測網頁編碼,當你使用r.text時,requests就會使用這個編碼。當然你還可以修改requests的編碼形式。
>>>r=requests.get('http://www.zhidaow.com')>>>r.encoding'utf-8'>>>r.encoding='ISO-8859-1'
像上面的例子,對encoding修改后就直接會用修改后的編碼去獲取網頁內容。
3.5 json
像urllib和urllib2,如果用到json,就要引入新模塊,如json和simplejson,但在requests中已經有了內置的函數,r.json()。就拿查詢IP的API來說:
>>>r=requests.get('http://ip.taobao.com/service/getIpInfo.php?ip=122.88.60.28')>>>r.json()['data']['country']'中國'
3.6 網頁狀態碼
我們可以用r.status_code來檢查網頁的狀態碼。
>>>r=requests.get('http://www.mengtiankong.com')>>>r.status_code200>>>r=requests.get('http://www.mengtiankong.com/123123/')>>>r.status_code404>>>r=requests.get('http://www.baidu.com/link?url=QeTRFOS7TuUQRppa0wlTJJr6FfIYI1DJprJukx4Qy0XnsDO_s9baoO8u1wvjxgqN')>>>r.urlu'http://www.zhidaow.com/>>>r.status_code200
前兩個例子很正常,能正常打開的返回200,不能正常打開的返回404。但第三個就有點奇怪了,那個是百度搜索結果中的302跳轉地址,但狀態碼顯示是200,接下來我用了一招讓他原形畢露:
>>>r.history(,)
這里能看出他是使用了302跳轉。也許有人認為這樣可以通過判斷和正則來獲取跳轉的狀態碼了,其實還有個更簡單的方法:
>>>r=requests.get('http://www.baidu.com/link?url=QeTRFOS7TuUQRppa0wlTJJr6FfIYI1DJprJukx4Qy0XnsDO_s9baoO8u1wvjxgqN',allow_redirects=False)>>>r.status_code302
只要加上一個參數allow_redirects,禁止了跳轉,就直接出現跳轉的狀態碼了,好用吧?我也利用這個在最后一掌做了個簡單的獲取網頁狀態碼的小應用,原理就是這個。
3.7 響應頭內容
可以通過r.headers來獲取響應頭內容。
>>>r=requests.get('http://www.zhidaow.com')>>>r.headers{'content-encoding':'gzip','transfer-encoding':'chunked','content-type':'text/html;charset=utf-8';...}
可以看到是以字典的形式返回了全部內容,我們也可以訪問部分內容。
>>>r.headers['Content-Type']'text/html;charset=utf-8'>>>r.headers.get('content-type')'text/html;charset=utf-8'
3.8 設置超時時間
我們可以通過timeout屬性設置超時時間,一旦超過這個時間還沒獲得響應內容,就會提示錯誤。
>>>requests.get('http://github.com',timeout=0.001)Traceback(mostrecentcalllast):File"",line1,inrequests.exceptions.Timeout:HTTPConnectionPool(host='github.com',port=80):Requesttimedout.(timeout=0.001)
3.9代理訪問
采集時為避免被封IP,經常會使用代理。requests也有相應的proxies屬性。
importrequestsproxies={"http":"http://10.10.1.10:3128","https":"http://10.10.1.10:1080",}requests.get("http://www.zhidaow.com",proxies=proxies)
如果代理需要賬戶和密碼,則需這樣:
proxies={"http":"http://user:pass@10.10.1.10:3128/",}
3.10請求頭內容
請求頭內容可以用r.request.headers來獲取。
>>>r.request.headers{'Accept-Encoding':'identity,deflate,compress,gzip','Accept':'*/*','User-Agent':'python-requests/1.2.3 CPython/2.7.3 Windows/XP'}
3.11 自定義請求頭部
偽裝請求頭部是采集時經常用的,我們可以用這個方法來隱藏:
r=requests.get('http://www.zhidaow.com')printr.request.headers['User-Agent']#python-requests/1.2.3 CPython/2.7.3 Windows/XPheaders={'User-Agent':'alexkh'}r=requests.get('http://www.zhidaow.com',headers=headers)printr.request.headers['User-Agent']#alexkh
3.12持久連接keep-alive
requests的keep-alive是基于urllib3,同一會話內的持久連接完全是自動的。同一會話內的所有請求都會自動使用恰當的連接。
也就是說,你無需任何設置,requests會自動實現keep-alive。
4. 簡單應用
4.1 獲取網頁返回碼
defget_status(url):r=requests.get(url,allow_redirects=False)returnr.status_codeprintget_status('http://www.zhidaow.com')#200printget_status('http://www.zhidaow.com/hi404/')#404printget_status('http://mengtiankong.com')#301printget_status('http://www.baidu.com/link?url=QeTRFOS7TuUQRppa0wlTJJr6FfIYI1DJprJukx4Qy0XnsDO_s9baoO8u1wvjxgqN')#302printget_status('http://www.huiya56.com/com8.intre.asp?46981.html')#500
官方文檔
requests的具體安裝過程請看:http://docs.python-requests.org/en/latest/user/install.html#install
requests的官方指南文檔:http://docs.python-requests.org/en/latest/user/quickstart.html
requests的高級指南文檔:http://docs.python-requests.org/en/latest/user/advanced.html#advanced