06. Requests庫(kù)的用法
2. 安裝
利用 pip 安裝
pip install requests
3. 基本請(qǐng)求
req = requests.get("http://www.baidu.com")
req = requests.post("http://www.baidu.com")
req = requests.put("http://www.baidu.com")
req = requests.delete("http://www.baidu.com")
req = requests.head("http://www.baidu.com")
req = requests.options("http://www.baidu.com")
3.1 get請(qǐng)求
參數(shù)是字典,我們也可以傳遞json類型的參數(shù):
import requests
url = "http://www.baidu.com/s"
params = {'wd': '尚學(xué)堂'}
response = requests.get(url, params=params)
print(response.url)
response.encoding = 'utf-8'
html = response.text
# print(html)
3.2 post請(qǐng)求
參數(shù)是字典,我們也可以傳遞json類型的參數(shù):
url = "http://www.sxt.cn/index/login/login.html"
formdata = {
? ?"user": "17703181473",
? ?"password": "123456"
}
response = requests.post(url, data=formdata)
response.encoding = 'utf-8'
html = response.text
# print(html)
3.3 自定義請(qǐng)求頭部
偽裝請(qǐng)求頭部是采集時(shí)經(jīng)常用的,我們可以用這個(gè)方法來(lái)隱藏:
headers = {'User-Agent': 'python'}
r = requests.get('http://www.zhidaow.com', headers = headers)
print(r.request.headers['User-Agent'])
3.4 設(shè)置超時(shí)時(shí)間
可以通過(guò)timeout屬性設(shè)置超時(shí)時(shí)間,一旦超過(guò)這個(gè)時(shí)間還沒(méi)獲得響應(yīng)內(nèi)容,就會(huì)提示錯(cuò)誤
requests.get('http://github.com', timeout=0.001)
3.5 代理訪問(wèn)
采集時(shí)為避免被封IP,經(jīng)常會(huì)使用代理。requests也有相應(yīng)的proxies屬性
import requests
proxies = {
?"http": "http://10.10.1.10:3128",
?"https": "https://10.10.1.10:1080",
}
requests.get("http://www.zhidaow.com", proxies=proxies)
如果代理需要賬戶和密碼,則需這樣
proxies = {
? ?"http": "http://user:pass@10.10.1.10:3128/",
}
3.6 session自動(dòng)保存cookies
seesion的意思是保持一個(gè)會(huì)話,比如 登陸后繼續(xù)操作(記錄身份信息) 而requests是單次請(qǐng)求的請(qǐng)求,身份信息不會(huì)被記錄
# 創(chuàng)建一個(gè)session對(duì)象
s = requests.Session()
# 用session對(duì)象發(fā)出get請(qǐng)求,設(shè)置cookies
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
3.7 ssl驗(yàn)證
# 禁用安全請(qǐng)求警告
requests.packages.urllib3.disable_warnings()
resp = requests.get(url, verify=False, headers=headers)
4 獲取響應(yīng)信息
代碼含義resp.json()獲取響應(yīng)內(nèi)容(以json字符串)resp.text獲取響應(yīng)內(nèi)容 (以字符串)resp.content獲取響應(yīng)內(nèi)容(以字節(jié)的方式)resp.headers獲取響應(yīng)頭內(nèi)容resp.url獲取訪問(wèn)地址resp.encoding獲取網(wǎng)頁(yè)編碼resp.request.headers請(qǐng)求頭內(nèi)容resp.cookie