Requests庫(kù)是由python語(yǔ)言編寫的HTTP客戶端庫(kù),常用于編寫爬蟲和測(cè)試服務(wù)器響應(yīng)數(shù)據(jù)从撼。
1. 安裝Requests
Windows系統(tǒng)下怜森,在命令行輸入:pip install requests,安裝
2. 方法函數(shù)-get()
r=requests.get(url,params,**kwargs)
url: 需要爬取的網(wǎng)站地址暇咆。
params: 翻譯過來(lái)就是參數(shù)锋爪, url中的額外參數(shù)丙曙,字典或者字節(jié)流格式,可選其骄。
**kwargs : 12個(gè)控制訪問的參數(shù)
r對(duì)象的屬性:
r.status_code http請(qǐng)求的返回狀態(tài)亏镰,若為200則表示請(qǐng)求成功。
r.text http響應(yīng)內(nèi)容的字符串形式拯爽,即返回的頁(yè)面內(nèi)容
r.encoding 從http header 中猜測(cè)的相應(yīng)內(nèi)容編碼方式
r.apparent_encoding 從內(nèi)容中分析出的響應(yīng)內(nèi)容編碼方式(備選編碼方式)
r.content http響應(yīng)內(nèi)容的二進(jìn)制形式
使用實(shí)例1:不帶參數(shù)的get
>>> import requests
>>>r=requests.get('https://www.baidu.com')
>>> print r
出現(xiàn)<Response [200]>索抓,說明請(qǐng)求成功
>>> print r.encoding
ISO-8859-1
requests會(huì)從服務(wù)器返回的響應(yīng)頭的 Content-Type 去獲取字符集編碼,如果content-type有charset字段那么requests才能正確識(shí)別編碼毯炮,否則就使用默認(rèn)的 ISO-8859-1. 一般那些不規(guī)范的頁(yè)面往往有這樣的問題.
解決辦法:
requests的返回結(jié)果對(duì)象里有個(gè)apparent_encoding函數(shù), 通過調(diào)用chardet.detect()來(lái)識(shí)別文本編碼
>>> r.apparent_encoding
'utf-8'
>>> r.encoding='utf-8'
>>> r.text
此時(shí)正確打印出頁(yè)面HTML
使用實(shí)例2:傳遞參數(shù)
參數(shù)以鍵/值對(duì)的形式置于 URL 中逼肯,跟在一個(gè)問號(hào)的后面
>>> payload = {'key1': 'value1', 'key2': 'value2', 'key3': None}
>>>r=requests.get('http://httpbin.org/get',params=payload)
>>> print(r.url)
http://httpbin.org/get?key2=value2&key1=value1
使用實(shí)例3:傳遞headers
>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> r = requests.get(url, headers=headers)
使用實(shí)例4:傳遞cookies
>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')
>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'
參考來(lái)源:http://docs.python-requests.org/zh_CN/latest/index.html