最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會(huì)員登陸 & 注冊(cè)

06. Requests庫(kù)的用法

2020-06-29 10:32 作者:自學(xué)Python的小姐姐呀  | 我要投稿

1. 介紹

對(duì)了解一些爬蟲(chóng)的基本理念,掌握爬蟲(chóng)爬取的流程有所幫助。入門(mén)之后,我們就需要學(xué)習(xí)一些更加高級(jí)的內(nèi)容和工具來(lái)方便我們的爬取。那么這一節(jié)來(lái)簡(jiǎn)單介紹一下 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獲取cookie


06. Requests庫(kù)的用法的評(píng)論 (共 條)

分享到微博請(qǐng)遵守國(guó)家法律
怀仁县| 灵台县| 吉林市| 荣成市| 裕民县| 武清区| 礼泉县| 军事| 柳林县| 榆中县| 刚察县| 从化市| 曲阳县| 新邵县| 苏尼特左旗| 青河县| 五大连池市| 昔阳县| 孝感市| 阿拉善左旗| 房产| 利津县| 喀喇| 白城市| 马关县| 武川县| 合肥市| 永清县| 拉孜县| 新郑市| 南阳市| 自贡市| 横山县| 新民市| 丰镇市| 葫芦岛市| 厦门市| 府谷县| 达拉特旗| 颍上县| 班玛县|