一、介紹
Requests 是用Python語言編寫,基于 urllib,采用 Apache2 Licensed 開源協(xié)議的 HTTP 庫。它比 urllib 更加方便,可以節(jié)約我們大量的工作,完全滿足 HTTP 測試需求。Requests 的哲學(xué)是以 PEP 20 的習(xí)語為中心開發(fā)的,所以它比 urllib 更加 Pythoner。更重要的一點是它支持 Python3!
二、安裝
- pip安裝
pip install requests
- GitHub下載安裝
$ git clone git://github.com/kennethreitz/requests.git
$ cd requests
$ python setup.py install
三、使用
Request庫的幾個主要方法
- requests.request():構(gòu)造一個請求,支持以下各種方法
- requests.get():獲取html的主要方法
- requests.head():獲取html頭部信息的主要方法
- requests.post():向html網(wǎng)頁提交post請求的方法
- requests.put():向html網(wǎng)頁提交put請求的方法
- requests.patch():向html提交局部修改的請求
- requests.delete():向html提交刪除請求
requests.get()
# 具體參數(shù)
requests.get(url,params,**kwargs)
- url: 需要爬取的網(wǎng)站地址。
- params: 參數(shù),使用這個參數(shù)可以把一些鍵值對以?key1=value1&key2=value2的模式增加到url中
- **kwargs : 12個控制訪問的參數(shù)
- 簡單的使用
import requests
response = requests.get('https://www.baidu.com') # 最基本的GET請求
print(response .status_code) # 獲取返回狀態(tài)
- 12個**kwargs
- data:字典,字節(jié)序或文件對象,重點作為向服務(wù)器提供或提交資源是提交。作為request的內(nèi)容,與params不同的是,data提交的數(shù)據(jù)并不放在url鏈接里, 而是放在url鏈接對應(yīng)位置的地方作為數(shù)據(jù)來存儲。它也可以接受一個字符串對象。
- json:json格式的數(shù)據(jù), json合適在相關(guān)的html,http相關(guān)的web開發(fā)中非常常見, 也是http最經(jīng)常使用的數(shù)據(jù)格式, 他是作為內(nèi)容部分可以向服務(wù)器提交。
- headers:字典是http的相關(guān)語,對應(yīng)了向某個url訪問時所發(fā)起的http的頭i字段, 可以用這個字段來定義http的訪問的http頭,可以用來模擬任何我們想模擬的瀏覽器來對url發(fā)起訪問。
- cookies:字典或CookieJar,指的是從http中解析cookie
- auth:元組,用來支持http認證功能
- files:字典, 是用來向服務(wù)器傳輸文件時使用的字段。
- timeout: 用于設(shè)定超時時間, 單位為秒,當發(fā)起一個get請求時可以設(shè)置一個timeout時間, 如果在timeout時間內(nèi)請求內(nèi)容沒有返回, 將產(chǎn)生一個timeout的異常。
- proxies:字典, 用來設(shè)置訪問代理服務(wù)器。
- allow_redirects: 開關(guān), 表示是否允許對url進行重定向, 默認為True。
- stream: 開關(guān), 指是否對獲取內(nèi)容進行立即下載, 默認為True。
- verify:開關(guān), 用于認證SSL證書, 默認為True。
- cert: 用于設(shè)置保存本地SSL證書路徑
- 帶參數(shù)的Get請求
# 復(fù)雜的get請求
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'}
url = "https://www.baidu.com/s"
params = {
"ie":"utf-8",
"kw":"?;?
}
r = requests.get(url=url,headers=headers,params=params)
# get請求的參數(shù)用params形參來接收,接收的時候字典就行
print(r.status_code)
- 獲取cookies
import requests
r = requests.get('http://www.google.com.hk/')
print(r.cookies['NID'])
print(tuple(r.cookies))
對于某些需要登錄才能訪問的網(wǎng)站,獲取到Cookies后,下次請求時我們可以攜帶Cookies進行網(wǎng)站的訪問
- 攜帶cookie
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())
requests有一個Session對象可以用于保存會話。練習(xí)將使用Session對象來保存對話
- 上傳文件
# 上傳圖片
import requests
url = 'http://127.0.0.1:5000/upload'
files = {'file': open('./test.jpg', 'rb')}
#files = {'file': ('test.jpg', open('/test.jpg', '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)
- 使用代理
import requests
proxies = {
"http": "http://10.10.1.10:3128",
"https": "http://10.10.1.10:1080",
}
requests.get("http://www.zhidaow.com", proxies=proxies)
response的對象屬性
- 對象屬性
- status_code:請求的返回狀態(tài),若為200則表示請求成功。
- text:響應(yīng)內(nèi)容的字符串形式,即返回的頁面內(nèi)容
- encoding:從http header 中猜測的相應(yīng)內(nèi)容編碼方式
- apparent_encoding:從內(nèi)容中分析出的響應(yīng)內(nèi)容編碼方式(備選編碼方式)
- content:響應(yīng)內(nèi)容的二進制形式返回
- 使用
>>> import requests
>>> r=requests.get("http://www.baidu.com")
>>> r.status_code
200
>>> r.encoding
'ISO-8859-1'
>>> r.apparent_encoding
'utf-8'
>>> r.content
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8>ipt> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">?\x9b′?¤\x9a?o§?\x93\x81</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a com/ class=cp-feedback>?\x84\x8fè§\x81?\x8f\x8dé|\x88</a> ?o?ICPèˉ\x81030173?\x8f· <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'
>>> r.encoding='utf-8'
>>> r.text
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta chref=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css="h讀</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>意見反饋</a> 京ICP證030173號 <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'
練習(xí)
- 微博登錄
import requests
# 主頁url
url = "https://weibo.cn/6370062528/info"
# 登錄接口
login_url = "https://passport.weibo.cn/sso/login"
# 請求頭
headers = {
'Accept': '*/*',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Content-Type': 'application/x-www-form-urlencoded',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36',
'Host': 'passport.weibo.cn',
'Origin': 'https://passport.weibo.cn',
'Referer': 'https://passport.weibo.cn/signin/login?entry=mweibo&r=https%3A%2F%2Fweibo.cn%2F%3Fluicode%3D20000174&backTitle=%CE%A2%B2%A9&vt='
}
# 請求體
data = {
'username':'USERNAME',
'password': 'PASSWORD',
'savestate':'1',
'r': 'https://weibo.cn/?luicode=20000174',
'ec': '0',
'pagerefer': 'https://weibo.cn/pub/?vt=',
'entry': 'mweibo',
'wentry':'',
'loginfrom':'',
'client_id':'',
'code':'',
'qq':'',
'mainpageflag': '1',
'hff':'',
'hfp':''
}
# r = requests.post(url=login_url,data=data,headers=headers)
# 【注意】requests無法保存會話信息
# requests有一個Session對象可以用于保存會話。這樣在我們登錄完成后就可以再訪問主頁了。當然你也可以選擇不使用Session來保存會話,而選擇在登錄完成后再訪問主頁的時候攜帶你的cookies。
s = requests.Session()
r = s.post(url=login_url,data=data,headers=headers)
print(r.text)
res = s.get(url=url,headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'})
print(res.status_code)
with open("weibo.html",'wb') as fp:
fp.write(res.content)