2019-01-09 python 庫之 requests

python 庫之 requests

Requests 是用Python語言編寫,基于 urllib,采用 Apache2 Licensed 開源協(xié)議的 HTTP 庫。它比 urllib 更加方便,可以節(jié)約我們大量的工作,完全滿足 HTTP 測試需求。Requests 的哲學是以 PEP 20 的習語為中心開發(fā)的,所以它比 urllib 更加 Pythoner。更重要的一點是它支持 Python3 哦!

Beautiful is better than ugly.(美麗優(yōu)于丑陋)

Explicit is better than implicit.(清楚優(yōu)于含糊)

Simple is better than complex.(簡單優(yōu)于復雜)

Complex is better than complicated.(復雜優(yōu)于繁瑣)

Readability counts.(重要的是可讀性)

一、安裝 Requests

通過pip安裝

pip install requests

或者,下載代碼后安裝:

$ git clone git://github.com/kennethreitz/requests.git

$ cd requests

$ python setup.py install

再懶一點,通過IDE安裝吧,如pycharm!

二、發(fā)送請求與傳遞參數(shù)

先來一個簡單的例子吧!讓你了解下其威力:

import requests

r = requests.get(url='http://www.itwhy.org')? ? # 最基本的GET請求

print(r.status_code)? ? # 獲取返回狀態(tài)

r = requests.get(url='http://dict.baidu.com/s', params={'wd':'python'})? #帶參數(shù)的GET請求

print(r.url)

print(r.text)? #打印解碼后的返回數(shù)據(jù)

很簡單吧!不但GET方法簡單,其他方法都是統(tǒng)一的接口樣式哦!

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系統(tǒng)一般只支持 GET 和 POST,有一些還支持 HEAD 方法。

帶參數(shù)的請求實例:

import requests

requests.get('http://www.dict.baidu.com/s', params={'wd': 'python'})? ? #GET參數(shù)實例

requests.post('http://www.itwhy.org/wp-comments-post.php', data={'comment': '測試POST'})? ? #POST參數(shù)實例

POST發(fā)送JSON數(shù)據(jù):

import requests

import json

r = requests.post('https://api.github.com/some/endpoint', data=json.dumps({'some': 'data'}))

print(r.json())

定制header:

import requests

import json

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對象,其存儲了服務(wù)器響應(yīng)的內(nèi)容,如上實例中已經(jīng)提到的 r.text、r.status_code……

獲取文本方式的響應(yīng)體實例:當你訪問 r.text 之時,會使用其響應(yīng)的文本編碼進行解碼,并且你可以修改其編碼讓 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)

其他響應(yīng):

r.status_code #響應(yīng)狀態(tài)碼

r.raw #返回原始響應(yīng)體,也就是 urllib 的 response 對象,使用 r.raw.read() 讀取

r.content #字節(jié)方式的響應(yīng)體,會自動為你解碼 gzip 和 deflate 壓縮

r.text #字符串方式的響應(yīng)體,會自動根據(jù)響應(yīng)頭部的字符編碼進行解碼

r.headers #以字典對象存儲服務(wù)器響應(yīng)頭,但是這個字典比較特殊,字典鍵不區(qū)分大小寫,若鍵不存在則返回None

#*特殊方法*#

r.json() #Requests中內(nèi)置的JSON解碼器

r.raise_for_status() #失敗請求(非200響應(yīng))拋出異常

案例之一:

import requests

URL = 'http://ip.taobao.com/service/getIpInfo.php'? # 淘寶IP地址庫API

try:

? ? r = requests.get(URL, params={'ip': '8.8.8.8'}, timeout=1)

? ? r.raise_for_status()? ? # 如果響應(yīng)狀態(tài)碼不是 200,就主動拋出異常

except requests.RequestException as e:

? ? print(e)

else:

? ? result = r.json()

? ? print(type(result), result, sep='\n')

四、上傳文件

使用 Requests 模塊,上傳文件也是如此簡單的,文件的類型會自動進行處理:

import requests

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'))}? ? #顯式的設(shè)置文件名

r = requests.post(url, files=files)

print(r.text)

更加方便的是,你可以把字符串當著文件進行上傳:

import requests

url = 'http://127.0.0.1:5000/upload'

files = {'file': ('test.txt', b'Hello Requests.')}? ? #必需顯式的設(shè)置文件名

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與會話對象

如果某個響應(yīng)中包含一些Cookie,你可以快速訪問它們:

import requests

r = requests.get('http://www.google.com.hk/')

print(r.cookies['NID'])

print(tuple(r.cookies))

要想發(fā)送你的cookies到服務(wù)器,可以使用 cookies 參數(shù):

import requests

url = 'http://httpbin.org/cookies'

cookies = {'testCookies_1': 'Hello_Python3', 'testCookies_2': 'Hello_Requests'}

# 在Cookie Version 0中規(guī)定空格、方括號、圓括號、等于號、逗號、雙引號、斜杠、問號、@,冒號,分號等特殊符號都不能作為Cookie的內(nèi)容。

r = requests.get(url, cookies=cookies)

print(r.json())

會話對象讓你能夠跨請求保持某些參數(shù),最方便的是在同一個Session實例發(fā)出的所有請求之間保持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 僅對連接過程有效,與響應(yīng)體的下載無關(guān)。

>>> 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)

所有Requests顯式拋出的異常都繼承自 requests.exceptions.RequestException:ConnectionError、HTTPError、Timeout、TooManyRedirects。

轉(zhuǎn)自:http://www.itwhy.org/%E8%BD%AF%E4%BB%B6%E5%B7%A5%E7%A8%8B/Python/python-%E7%AC%AC%E4%B8%89%E6%96%B9-http-%E5%BA%93-requests-%E5%AD%A6%E4%B9%A0.html


requests是python的一個HTTP客戶端庫,跟urllib,urllib2類似,那為什么要用requests而不用urllib2呢?官方文檔中是這樣說明的:

python的標準庫urllib2提供了大部分需要的HTTP功能,但是API太逆天了,一個簡單的功能就需要一大堆代碼。

我也看了下requests的文檔,確實很簡單,適合我這種懶人。下面就是一些簡單指南。

插播個好消息!剛看到requests有了中文翻譯版,建議英文不好的看看,內(nèi)容也比我的博客好多了,具體鏈接是:http://cn.python-requests.org/en/latest/(不過是v1.1.0版,另抱歉,之前貼錯鏈接了)。

1. 安裝

安裝很簡單,我是win系統(tǒng),就在這里下載了安裝包(網(wǎng)頁中download the zipball處鏈接),然后$ python setup.py install就裝好了。

當然,有easy_install或pip的朋友可以直接使用:easy_install requests或者pip install requests來安裝。

至于linux用戶,這個頁面還有其他安裝方法。

測試:在IDLE中輸入import requests,如果沒提示錯誤,那說明已經(jīng)安裝成功了!

2. 小試牛刀

>>>importrequests>>>r=requests.get('http://www.zhidaow.com')# 發(fā)送請求>>>r.status_code# 返回碼200>>>r.headers['content-type']# 返回頭部信息'text/html; charset=utf8'>>>r.encoding# 編碼信息'utf-8'>>>r.text#內(nèi)容部分(PS,由于編碼問題,建議這里使用r.content)u'\n

是不是很簡單?比urllib2和urllib簡單直觀的多?!那請接著看快速指南吧。

3. 快速指南

3.1 發(fā)送請求

發(fā)送請求很簡單的,首先要導入requests模塊:

>>>importrequests

接下來讓我們獲取一個網(wǎng)頁,例如我個人博客的首頁:

>>>r=requests.get('http://www.zhidaow.com')

接下來,我們就可以使用這個r的各種方法和函數(shù)了。

另外,HTTP請求還有很多類型,比如POST,PUT,DELETE,HEAD,OPTIONS。也都可以用同樣的方式實現(xiàn):

>>>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中傳遞參數(shù)

有時候我們需要在URL中傳遞參數(shù),比如在采集百度搜索結(jié)果時,我們wd參數(shù)(搜索詞)和rn參數(shù)(搜素結(jié)果數(shù)量),你可以手工組成URL,requests也提供了一種看起來很NB的方法:

>>>payload={'wd':'張亞楠','rn':'100'}>>>r=requests.get("http://www.baidu.com/s",params=payload)>>>printr.urlu'http://www.baidu.com/s?rn=100&wd=%E5%BC%A0%E4%BA%9A%E6%A5%A0'

上面wd=的亂碼就是“張亞楠”的轉(zhuǎn)碼形式。(好像參數(shù)按照首字母進行了排序。)

3.3 獲取響應(yīng)內(nèi)容

可以通過r.text來獲取網(wǎng)頁的內(nèi)容。

>>>r=requests.get('https://www.zhidaow.com')>>>r.textu'\n<html xmlns="http://www.w3.org/1999/xhtml"...'

文檔里說,requests會自動將內(nèi)容轉(zhuǎn)碼。大多數(shù)unicode字體都會無縫轉(zhuǎn)碼。但我在cygwin下使用時老是出現(xiàn)UnicodeEncodeError錯誤,郁悶。倒是在python的IDLE中完全正常。

另外,還可以通過r.content來獲取頁面內(nèi)容。

>>>r=requests.get('https://www.zhidaow.com')>>>r.contentb'\n<html xmlns="http://www.w3.org/1999/xhtml"...'

文檔中說r.content是以字節(jié)的方式去顯示,所以在IDLE中以b開頭。但我在cygwin中用起來并沒有,下載網(wǎng)頁正好。所以就替代了urllib2的urllib2.urlopen(url).read()功能。(基本上是我用的最多的一個功能。)

3.4 獲取網(wǎng)頁編碼

可以使用r.encoding來獲取網(wǎng)頁編碼。

>>>r=requests.get('http://www.zhidaow.com')>>>r.encoding'utf-8'

當你發(fā)送請求時,requests會根據(jù)HTTP頭部來猜測網(wǎng)頁編碼,當你使用r.text時,requests就會使用這個編碼。當然你還可以修改requests的編碼形式。

>>>r=requests.get('http://www.zhidaow.com')>>>r.encoding'utf-8'>>>r.encoding='ISO-8859-1'

像上面的例子,對encoding修改后就直接會用修改后的編碼去獲取網(wǎng)頁內(nèi)容。

3.5 json

像urllib和urllib2,如果用到j(luò)son,就要引入新模塊,如json和simplejson,但在requests中已經(jīng)有了內(nèi)置的函數(shù),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 網(wǎng)頁狀態(tài)碼

我們可以用r.status_code來檢查網(wǎng)頁的狀態(tài)碼。

>>>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。但第三個就有點奇怪了,那個是百度搜索結(jié)果中的302跳轉(zhuǎn)地址,但狀態(tài)碼顯示是200,接下來我用了一招讓他原形畢露:

>>>r.history(,)

這里能看出他是使用了302跳轉(zhuǎn)。也許有人認為這樣可以通過判斷和正則來獲取跳轉(zhuǎn)的狀態(tài)碼了,其實還有個更簡單的方法:

>>>r=requests.get('http://www.baidu.com/link?url=QeTRFOS7TuUQRppa0wlTJJr6FfIYI1DJprJukx4Qy0XnsDO_s9baoO8u1wvjxgqN',allow_redirects=False)>>>r.status_code302

只要加上一個參數(shù)allow_redirects,禁止了跳轉(zhuǎn),就直接出現(xiàn)跳轉(zhuǎn)的狀態(tài)碼了,好用吧?我也利用這個在最后一掌做了個簡單的獲取網(wǎng)頁狀態(tài)碼的小應(yīng)用,原理就是這個。

3.7 響應(yīng)頭內(nèi)容

可以通過r.headers來獲取響應(yīng)頭內(nèi)容。

>>>r=requests.get('http://www.zhidaow.com')>>>r.headers{'content-encoding':'gzip','transfer-encoding':'chunked','content-type':'text/html; charset=utf-8';...}

可以看到是以字典的形式返回了全部內(nèi)容,我們也可以訪問部分內(nèi)容。

>>>r.headers['Content-Type']'text/html; charset=utf-8'>>>r.headers.get('content-type')'text/html; charset=utf-8'

3.8 設(shè)置超時時間

我們可以通過timeout屬性設(shè)置超時時間,一旦超過這個時間還沒獲得響應(yīng)內(nèi)容,就會提示錯誤。

>>>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,經(jīng)常會使用代理。requests也有相應(yīng)的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 請求頭內(nèi)容

請求頭內(nèi)容可以用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 自定義請求頭部

偽裝請求頭部是采集時經(jīng)常用的,我們可以用這個方法來隱藏:

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,同一會話內(nèi)的持久連接完全是自動的。同一會話內(nèi)的所有請求都會自動使用恰當?shù)倪B接。

也就是說,你無需任何設(shè)置,requests會自動實現(xiàn)keep-alive。

4. 簡單應(yīng)用

4.1 獲取網(wǎng)頁返回碼

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

后記

1、官方文檔

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

2、本文內(nèi)容部分翻譯自官方文檔,部分自己歸納。

3、大多數(shù)用的IDLE格式,累死了,下次直接用編輯器格式,這樣更符合我的習慣。

4、還是那句話,有問題留言或email。

5、圖注:requests官方文檔上的一只老鱉。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容