之前學過urllib,但在實現功能時有些比較複雜,比如處理網頁驗證的cookies時,需要寫opener和handle來處理。爲了更加方便的實現這些操作,這就有了更爲強大的庫request,有了它,cookies、登錄驗證、代理設置等操作都不是事。
加載庫:
import requests
1.實現get請求(還有其他參數後面介紹)
r = requests.get('http://baidu.com')
1.1 實例化對象r的一些方法:
type(r) # 實例化對象的類型:requests.models.Response
r.status_code # 狀態碼
type(r.text) # 響應體爲str格式(有時是JSON格式,JSON = str(字典)則需要用json()方法轉換爲字典)
r.text # 響應體(返回的網頁,後續提取網頁信息)
r.cookies # 得到cookies
r.headers # 獲取響應頭
r.url # 獲取URL
r.history
1.2 除了get請求外,類似的實現其他請求(還有其他參數後面介紹)
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')
1.3 在get請求中加入一些參數(等於加在網址上)
data = {
'name':'daguo',
'age':'23'
} # 添加get信息,相當於在url後附加:http://httpbin.org/get?age=22&name=daguo
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
} # 添加請求頭
r = requests.get('http://httpbin.org/get',params=data, headers = headers) # params:參數
2. 抓取二進制文件並保存(下載:圖片、音樂、電影)
r = requests.get('https://github.com/favicon.ico') # 獲取二進制文件的鏈接
with open('favicon.ico','wb') as f: # 新建文件二進制寫入
f.write(r.content)
# 這裏用r.content:爲r中包含的原始內容(此處爲二進制格式,直接寫入即可)
# 不用r.text:因爲text將r中內容轉換爲了字符串格式(r.text = str(r.content))
3. POST請求
r = requests.post('http://httpbin.org/post')
3.1 提交表單
data = {
'name':'daguo',
'age':'23'
} # 添加表單
# GET請求中的data是添加參數(args),相當於修改URL,params = data
# POST請求中的data是添加表單(form),能提供更多信息,data = data
r = requests.post('http://httpbin.org/get',data = data)
3.2 文件上傳
files = {'file':open('favicon.ico','rb')} # 以字典的形式上傳文件
r = requests.post('http://httpbin.org/post',files = files)
3.3 獲取和設置cookies(可以直接通過請求頭設置)
# 獲取cookies
r = requests.get('http://www.baidu.com')
print(r.cookies) # 獲取
# cookies裏面都是一個個鍵值對,爲方便咱看:
# 用item()將cookies裝化成元組組成的列表
for key,value in r.cookies.items():
print(key + '=' + value)
# 設置cookies
headers = {
'Cookie':'從瀏覽器複製的已登錄的Cookies',
'Host':'www.zhihu.com',
'User-Agent':'從瀏覽器複製下來'
} # 通過請求頭設置Cookies
r = requests.get('https://www.zhihu.com',headers=headers)
3.4 保持會話(Session)
使會話保持連續,即cookies動態變化,不需要手動操控
s = requests.Session()
s.get('http://httpbin.org/cookies/set/number/123456789')
r = s.get('http://httpbin.org/cookies')
print(r.text)
# 運行結果
{
'cookies':{
'number':123456789
}
}
SSL證書驗證
有的網站需要驗證證書,沒證書不讓訪問
通過verify強制讓網站不驗證
verify = True(驗證)
verify = False(驗證)
r = requests.get('https://www.12306.cn',varify = False)
雖然不驗證但是有個警告建議驗證
解決方案有三種:1.忽略警告;2.捕獲警告到日誌;3.指定本地證書進行驗證
1.忽略警告
import requests
from requests.packages import urllib3
urllib3.disable_warnings()
r = requests.get('https://www.12306.cn',varify = False)
2.捕獲警告到日誌
import logging
import requests
logging.captureWarnings(True)
r = requests.get('https://www.12306.cn',varify = False)
3.指定本地證書進行驗證
本地需要有crt和key(解密狀態)
import requests
r = requests.get('https://www.12306.cn',cert = ('/path/server.crt','/path/key'))
代理設置
普通代理proxies
proxies = {
'http':'http://10.10.1.10:3128'
'https':'http://10.10.1.10.1080'
}
r = requests.get('https://www.taobao.com',proxies = proxies)
需要使用HTTP Basic Auth 的代理
代理格式:http://user:password@host:port
proxies = {
'http':'http://user:[email protected]:3128'
'https':'http://user:[email protected]'
}
r = requests.get('https://www.taobao.com',proxies = proxies)
SOCKS協議的代理(需要安裝:request[socks])
proxies = {
'http':'socks5://user:[email protected]:3128'
}
r = requests.get('https://www.taobao.com',proxies = proxies)
超時設置
import requests
# 默認timeout = None:永久等待
r = requests.get('http://www.taobao.com',timeout = 1)
身份認證(賬號密碼)
import requests
r = requests.get('http://localhost:5000',auth = ('username','password'))
Prepared Request
通過Request對象來設置所有參數(建議使用)
from requests import Request, Session
url = 'http://httpbin.org/post'
data = {
'name':'daguo'
}
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
} # 添加請求頭
s = Session()
req = Request('POST',url, data=data, headers=headers) # 用參數構造Request對象
preppd = s.prepare_request(req) # 將Request對象轉換爲Prepared Request對象
r = s.send(preppd) # 將Prepared Request對象發送給r
print(r.text)