爬蟲第二講:重要的requests庫

Requests庫

什么是Request庫

Requests是用Python語言編寫传透,基于urllib琳水,采用Apache2 Licensed開源協(xié)議的HTTP庫次和。它比urllib更加方便濒旦,可以節(jié)約我們大量的工作者春,完全滿足HTTP測試需求巨朦。一句話--Python實(shí)現(xiàn)的簡單易用的HTTP庫蝎亚。

安裝Requests

pip3 install requests

request詳解

  • 實(shí)例引入
import requests
response = requests.get('https://www.baidu.com')
print(type(response)) #<class 'requests.models.Response'>
print(response.status_code) #200
print(type(response.text))#class'str'
print(response.text)#響應(yīng)的內(nèi)容登颓,返回的頁面html
print(response.cookies)#<RequestsCookieJar[<Cookie  BDORZ=27315 for .baidu.com/>]>

  • 各種請(qǐng)求方法
import requests
requests.post('http://httpbin.org/post')
requests.put('http://httpbin.org/put')
requests.delete('http://httpbin.org/delete')
requests.head('http://httpbin.org/get')
requests.options('http://httpbin.org/get')
  • 請(qǐng)求
    1.基本用法
import requests
#response = requests.get('http://www.baidu.com')
response = requests.get('http://httpbin.org/get')
print(response.text)

2.帶參數(shù)的get請(qǐng)求

import requests
response = requests.get("http://httpbin.org/get?name=xiexie&age=22")
print(response.text)

這個(gè)參數(shù)編寫起來蠻復(fù)雜的月帝,以下是更清楚的做法躏惋,使用帶參數(shù)的requests.get方法

import requests
data = {
        'name':'xiexie',
        'age':89
        }
response = requests.get('http://httpbin.org/get',params=data)
print(response.text)

3.解析Json

import requests
response = requests.get('http://httpbin.org/get')
print(response.text)
print(response.json())
print(type(response.json()))

這在ajax請(qǐng)求時(shí)比較常用
4.獲取二進(jìn)制數(shù)據(jù)

import requests
response = requests.get('https://github.com/favicon.ico')
print(type(response.text),type(response.content))
print(response.text)
print(response.content)

response.text是string類型,而response.content是二進(jìn)制流
保存二進(jìn)制流到本地嚷辅,圖片簿姨、視頻、音頻都可以

import requests
response = requests.get('http://github.com/favicon.ico')
with open('favicon.ico','wb') as f:
    f.write(response.content)
    f.close()

5.添加headers作為爬蟲來說,headers非常重要扁位,演戲演全套准潭。不然會(huì)被服務(wù)器識(shí)別出來被禁用。

import requests
response = requests.get('https://www.zhihu.com/explore')
print(response.text)

不用headers域仇,直接返回400 Bad Request 刑然,無法爬取,以下代碼添加headers就能爬取了

import requests
headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
        }
response = requests.get('https://www.zhihu.com/explore',headers=headers)
print(response.text)

6.基本POST請(qǐng)求,需要構(gòu)造formdata

import requests
data = {'name':'xiexie','age':33} #傳個(gè)字典
response = requests.post('http://httpbin.org/post',data=data)
print(response.text)

response詳解

  • response屬性
import requests
response = requests.get('http://www.reibang.com')
print(type(response.status_code),response.status_code)
print(type(response.headers),response.headers)
print(type(response.cookies),response.cookies)
print(type(response.url),response.url)
print(type(response.history),response.history)
import requests
response = requests.get('http://jianshu.com')
exit() if not response.status_code == 403 else print('Forbidden!')

request高級(jí)操作
1.文件上傳

import requests
files = {'file':open('favicon.ico','rb')}
response = requests.post('http://httpbin.org/post',files=files)
print(response.text)

2.獲取cookie

import requests
response = requests.get('https://www.baidu.com')
print(response.cookies)#response.cookies是一個(gè)列表
for key,value in response.cookies.items():
    print(key + "=" + value)

3.會(huì)話維持暇务,用來模擬登陸用的泼掠。
模擬登陸 非常常用

import requests
requests.get('http://httpbin.org/cookies/set/number/1234567')
response = requests.get('http://httpbin.org/cookies')
print(response.text)
這里使用set設(shè)置了一個(gè)cookie,本意是下一句使用requests.get調(diào)用時(shí)希望返回這個(gè)cookie垦细,實(shí)際返回cookies為空择镇。實(shí)際上調(diào)用2次requests.get是互相獨(dú)立的,相當(dāng)于用不同的瀏覽器打開網(wǎng)頁括改。如果想返回剛剛設(shè)置的cookie需要保持會(huì)話腻豌。以下是會(huì)話維持的代碼,相當(dāng)于用同一個(gè)瀏覽器打開嘱能。
import requests
s = requests.Session()
s.get('http://httpbin.org/cookies/set/number/1234567')
response = s.get('http://httpbin.org/cookies')
print(response.text)

返回值:{
"cookies": {
"number": "1234567"
}
}

證書驗(yàn)證
有時(shí)候打開https的網(wǎng)站吝梅,而這個(gè)網(wǎng)站提供的證書沒有通過驗(yàn)證,那么拋出ssl錯(cuò)誤導(dǎo)致程序中斷惹骂。為了防止這種情況苏携,可以用varify參數(shù)。

import requests
from requests.packages import urllib3
urllib3.disable_warnings()#調(diào)用原生的urllib3中的disable_warnings()可以消除警告信息析苫。
response = requests.get('https://www.12306.cn',verify=False)
print(response.status_code)

也可以手動(dòng)導(dǎo)入ca證書和key,這樣也不會(huì)彈出錯(cuò)誤

import requests
response = requests.get('https://www.12306.cn',cert={'parth/server.crt','/path/key'})
print(response.status_code)

代理設(shè)置

import request
proxies = {
    "http":"http://127.0.0.1:9998",
    "https":"https://127.0.0.1:9998",
}
response = requests.get("https://www.taobao.com",proxies=proxies)
print(response.status_code)

有用戶名密碼的代理

import request
proxies = {
    "http":"http://user:password@127.0.0.1:9998",
    }
response = requests.get("https://www.taobao.com",proxies=proxies)
print(response.status_code)

ssr這種類型的socks代理怎么使用穿扳?
安裝:pip3 install 'requests[socks]'

import requests
proxies = {
    "http":"sock5://127.0.0.1:9998",
    "https":"sock5://127.0.0.1:9998",
}
response = requests.get("https://www.taobao.com",proxies=proxies)
print(response.status_code)
}

超時(shí)設(shè)置

import requests
try:
    response = requests.get("http://httpbin.org/get",timeout=1)
    print(response.status_code)
except requests.ReadTimeout:
    print('Timeout')

認(rèn)證設(shè)置

import requests
response = requests.get("http://httpbin.org/get",auth=HTTPBasicAuth('user','123'))
print(response.status_code)

另一種字典的方式

import requests
response = requests.get("http://httpbin.org/get",auth={'user':'123'})
print(response.status_code)

異常處理衩侥,爬蟲的異常處理也很有必要

import requests
from requests.exceptions import ReadTimeout,ConnectionError,RequestException
try:
    response = requests.get("http://httpbin.org/get",timeout=0.2)
    print(response.status_code)
except ReadTimeout:
    print('Timeout')
except ConnectionError:
    print("Con error")
except RequestException:
    print('Error')
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市矛物,隨后出現(xiàn)的幾起案子茫死,更是在濱河造成了極大的恐慌,老刑警劉巖履羞,帶你破解...
    沈念sama閱讀 221,820評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件峦萎,死亡現(xiàn)場離奇詭異,居然都是意外死亡忆首,警方通過查閱死者的電腦和手機(jī)爱榔,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來糙及,“玉大人详幽,你說我怎么就攤上這事。” “怎么了唇聘?”我有些...
    開封第一講書人閱讀 168,324評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵版姑,是天一觀的道長。 經(jīng)常有香客問我迟郎,道長剥险,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,714評(píng)論 1 297
  • 正文 為了忘掉前任宪肖,我火速辦了婚禮表制,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘匈庭。我一直安慰自己夫凸,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,724評(píng)論 6 397
  • 文/花漫 我一把揭開白布阱持。 她就那樣靜靜地躺著夭拌,像睡著了一般。 火紅的嫁衣襯著肌膚如雪衷咽。 梳的紋絲不亂的頭發(fā)上鸽扁,一...
    開封第一講書人閱讀 52,328評(píng)論 1 310
  • 那天,我揣著相機(jī)與錄音镶骗,去河邊找鬼桶现。 笑死,一個(gè)胖子當(dāng)著我的面吹牛鼎姊,可吹牛的內(nèi)容都是我干的骡和。 我是一名探鬼主播,決...
    沈念sama閱讀 40,897評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼相寇,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼慰于!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起唤衫,我...
    開封第一講書人閱讀 39,804評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤婆赠,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后佳励,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體休里,經(jīng)...
    沈念sama閱讀 46,345評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,431評(píng)論 3 340
  • 正文 我和宋清朗相戀三年赃承,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了妙黍。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,561評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡瞧剖,死狀恐怖废境,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤噩凹,帶...
    沈念sama閱讀 36,238評(píng)論 5 350
  • 正文 年R本政府宣布巴元,位于F島的核電站,受9級(jí)特大地震影響驮宴,放射性物質(zhì)發(fā)生泄漏逮刨。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,928評(píng)論 3 334
  • 文/蒙蒙 一堵泽、第九天 我趴在偏房一處隱蔽的房頂上張望修己。 院中可真熱鬧,春花似錦迎罗、人聲如沸睬愤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽尤辱。三九已至,卻和暖如春厢岂,著一層夾襖步出監(jiān)牢的瞬間光督,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評(píng)論 1 272
  • 我被黑心中介騙來泰國打工塔粒, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留结借,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,983評(píng)論 3 376
  • 正文 我出身青樓卒茬,卻偏偏與公主長得像船老,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子圃酵,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,573評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • 上一篇:8.Urllib庫基本使用下一篇:10.正則表達(dá)式基礎(chǔ) requests是python實(shí)現(xiàn)的最簡單易用的H...
    在努力中閱讀 3,360評(píng)論 2 11
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理柳畔,服務(wù)發(fā)現(xiàn),斷路器辜昵,智...
    卡卡羅2017閱讀 134,702評(píng)論 18 139
  • 昨天荸镊,我們更多的討論了request的基礎(chǔ)API咽斧,讓我們對(duì)它有了基礎(chǔ)的認(rèn)知堪置。學(xué)會(huì)上一課程,我們已經(jīng)能寫點(diǎn)基本的爬蟲...
    阿爾卑斯山上的小灰兔閱讀 12,312評(píng)論 1 8
  • 國家電網(wǎng)公司企業(yè)標(biāo)準(zhǔn)(Q/GDW)- 面向?qū)ο蟮挠秒娦畔?shù)據(jù)交換協(xié)議 - 報(bào)批稿:20170802 前言: 排版 ...
    庭說閱讀 11,005評(píng)論 6 13
  • 相由心生 其實(shí)一個(gè)人的相貌是由心生出來的张惹,要想讓自己有氣質(zhì)舀锨,必須修煉內(nèi)心,要想讓人看起來好看宛逗,那必須要懂得衣服的搭配坎匿。
    天行健初九閱讀 127評(píng)論 0 0