本篇文章為大家展示了怎么在Python中通過(guò)設(shè)置Cookie解決網(wǎng)站攔截問(wèn)題,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。

Python是一種跨平臺(tái)的、具有解釋性、編譯性、互動(dòng)性和面向?qū)ο蟮哪_本語(yǔ)言,其最初的設(shè)計(jì)是用于編寫自動(dòng)化腳本,隨著版本的不斷更新和新功能的添加,常用于用于開(kāi)發(fā)獨(dú)立的項(xiàng)目和大型項(xiàng)目。
一. 網(wǎng)站分析與爬蟲攔截
當(dāng)我們打開(kāi)螞蟻短租搜索貴陽(yáng)市,反饋如下圖所示結(jié)果。

我們可以看到短租房信息呈現(xiàn)一定規(guī)律分布,如下圖所示,這也是我們要爬取的信息。

通過(guò)瀏覽器審查元素,我們可以看到需要爬取每條租房信息都位于<dd></dd>節(jié)點(diǎn)下。

很多人學(xué)習(xí)python,不知道從何學(xué)起。
很多人學(xué)習(xí)python,掌握了基本語(yǔ)法過(guò)后,不知道在哪里尋找案例上手。
很多已經(jīng)做案例的人,卻不知道如何去學(xué)習(xí)更加高深的知識(shí)。
那么針對(duì)這三類人,我給大家提供一個(gè)好的學(xué)習(xí)平臺(tái),免費(fèi)領(lǐng)取視頻教程,電子書籍,以及課程的源代碼!
QQ群:810735403
在定位房屋名稱,如下圖所示,位于<div class="room-detail clearfloat"></div>節(jié)點(diǎn)下。

接下來(lái)我們寫個(gè)簡(jiǎn)單的BeautifulSoup進(jìn)行爬取。
# -*- coding: utf-8 -*-
import urllib
import re
from bs4 import BeautifulSoup
import codecs
url = 'http://www.mayi.com/guiyang/?map=no'
response=urllib.urlopen(url)
contents = response.read()
soup = BeautifulSoup(contents, "html.parser")
print soup.title
print soup
#短租房名稱
for tag in soup.find_all('dd'):
for name in tag.find_all(attrs={"class":"room-detail clearfloat"}):
fname = name.find('p').get_text()
print u'[短租房名稱]', fname.replace('\n','').strip()但很遺憾,報(bào)錯(cuò)了,說(shuō)明螞蟻金服防范措施還是挺到位的。

添加消息頭的代碼如下所示,這里先給出代碼和結(jié)果,再教大家如何獲取Cookie。
# -*- coding: utf-8 -*-
import urllib2
import re
from bs4 import BeautifulSoup
#爬蟲函數(shù)
def gydzf(url):
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
headers={"User-Agent":user_agent}
request=urllib2.Request(url,headers=headers)
response=urllib2.urlopen(request)
contents = response.read()
soup = BeautifulSoup(contents, "html.parser")
for tag in soup.find_all('dd'):
#短租房名稱
for name in tag.find_all(attrs={"class":"room-detail clearfloat"}):
fname = name.find('p').get_text()
print u'[短租房名稱]', fname.replace('\n','').strip()
#短租房?jī)r(jià)格
for price in tag.find_all(attrs={"class":"moy-b"}):
string = price.find('p').get_text()
fprice = re.sub("[¥]+".decode("utf8"), "".decode("utf8"),string)
fprice = fprice[0:5]
print u'[短租房?jī)r(jià)格]', fprice.replace('\n','').strip()
#評(píng)分及評(píng)論人數(shù)
for score in name.find('ul'):
fscore = name.find('ul').get_text()
print u'[短租房評(píng)分/評(píng)論/居住人數(shù)]', fscore.replace('\n','').strip()
#網(wǎng)頁(yè)鏈接url
url_dzf = tag.find(attrs={"target":"_blank"})
urls = url_dzf.attrs['href']
print u'[網(wǎng)頁(yè)鏈接]', urls.replace('\n','').strip()
urlss = 'http://www.mayi.com' + urls + ''
print urlss
#主函數(shù)
if __name__ == '__main__':
i = 1
while i<10:
print u'頁(yè)碼', i
url = 'http://www.mayi.com/guiyang/' + str(i) + '/?map=no'
gydzf(url)
i = i+1
else:
print u"結(jié)束"輸出結(jié)果如下圖所示:
頁(yè)碼 1
[短租房名稱] 大唐東原財(cái)富廣場(chǎng)--城市簡(jiǎn)約復(fù)式民宿
[短租房?jī)r(jià)格] 298
[短租房評(píng)分/評(píng)論/居住人數(shù)] 5.0分·5條評(píng)論·二居·可住3人
[網(wǎng)頁(yè)鏈接] /room/851634765
http://www.mayi.com/room/851634765
[短租房名稱] 大唐東原財(cái)富廣場(chǎng)--清新檸檬復(fù)式民宿
[短租房?jī)r(jià)格] 568
[短租房評(píng)分/評(píng)論/居住人數(shù)] 2條評(píng)論·三居·可住6人
[網(wǎng)頁(yè)鏈接] /room/851634467
http://www.mayi.com/room/851634467
...
頁(yè)碼 9
[短租房名稱] 【高鐵北站公園旁】美式風(fēng)情+超大舒適安逸
[短租房?jī)r(jià)格] 366
[短租房評(píng)分/評(píng)論/居住人數(shù)] 3條評(píng)論·二居·可住5人
[網(wǎng)頁(yè)鏈接] /room/851018852
http://www.mayi.com/room/851018852
[短租房名稱] 大營(yíng)坡(中大國(guó)際購(gòu)物中心附近)北歐小清新三室
[短租房?jī)r(jià)格] 298
[短租房評(píng)分/評(píng)論/居住人數(shù)] 三居·可住6人
[網(wǎng)頁(yè)鏈接] /room/851647045
http://www.mayi.com/room/851647045

接下來(lái)我們想獲取詳細(xì)信息

這里作者主要是提供分析Cookie的方法,使用瀏覽器打開(kāi)網(wǎng)頁(yè),右鍵“檢查”,然后再刷新網(wǎng)頁(yè)。在“NetWork”中找到網(wǎng)頁(yè)并點(diǎn)擊,在彈出來(lái)的Headers中就隱藏這這些信息。

最常見(jiàn)的兩個(gè)參數(shù)是Cookie和User-Agent,如下圖所示:

然后在Python代碼中設(shè)置這些參數(shù),再調(diào)用Urllib2.Request()提交請(qǐng)求即可,核心代碼如下:
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) ... Chrome/61.0.3163.100 Safari/537.36"
cookie="mediav=%7B%22eid%22%3A%22387123...b3574ef2-21b9-11e8-b39c-1bc4029c43b8"
headers={"User-Agent":user_agent,"Cookie":cookie}
request=urllib2.Request(url,headers=headers)
response=urllib2.urlopen(request)
contents = response.read()
soup = BeautifulSoup(contents, "html.parser")
for tag1 in soup.find_all(attrs={"class":"main"}):注意,每小時(shí)Cookie會(huì)更新一次,我們需要手動(dòng)修改Cookie值即可,就是上面代碼的cookie變量和user_agent變量。完整代碼如下所示:
import urllib2
import re
from bs4 import BeautifulSoup
import codecs
import csv
c = open("ycf.csv","wb") #write 寫
c.write(codecs.BOM_UTF8)
writer = csv.writer(c)
writer.writerow(["短租房名稱","地址","價(jià)格","評(píng)分","可住人數(shù)","人均價(jià)格"])
#爬取詳細(xì)信息
def getInfo(url,fname,fprice,fscore,users):
#通過(guò)瀏覽器開(kāi)發(fā)者模式查看訪問(wèn)使用的user_agent及cookie設(shè)置訪問(wèn)頭(headers)避免反爬蟲,且每隔一段時(shí)間運(yùn)行要根據(jù)開(kāi)發(fā)者中的cookie更改代碼中的cookie
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"
cookie="mediav=%7B%22eid%22%3A%22387123%22eb7; mayi_uuid=1582009990674274976491; sid=42200298656434922.85.130.130"
headers={"User-Agent":user_agent,"Cookie":cookie}
request=urllib2.Request(url,headers=headers)
response=urllib2.urlopen(request)
contents = response.read()
soup = BeautifulSoup(contents, "html.parser")
#短租房地址
for tag1 in soup.find_all(attrs={"class":"main"}):
print u'短租房地址:'
for tag2 in tag1.find_all(attrs={"class":"desWord"}):
address = tag2.find('p').get_text()
print address
#可住人數(shù)
print u'可住人數(shù):'
for tag4 in tag1.find_all(attrs={"class":"w258"}):
yy = tag4.find('span').get_text()
print yy
fname = fname.encode("utf-8")
address = address.encode("utf-8")
fprice = fprice.encode("utf-8")
fscore = fscore.encode("utf-8")
fpeople = yy[2:3].encode("utf-8")
ones = int(float(fprice))/int(float(fpeople))
#存儲(chǔ)至本地
writer.writerow([fname,address,fprice,fscore,fpeople,ones])
#爬蟲函數(shù)
def gydzf(url):
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
headers={"User-Agent":user_agent}
request=urllib2.Request(url,headers=headers)
response=urllib2.urlopen(request)
contents = response.read()
soup = BeautifulSoup(contents, "html.parser")
for tag in soup.find_all('dd'):
#短租房名稱
for name in tag.find_all(attrs={"class":"room-detail clearfloat"}):
fname = name.find('p').get_text()
print u'[短租房名稱]', fname.replace('\n','').strip()
#短租房?jī)r(jià)格
for price in tag.find_all(attrs={"class":"moy-b"}):
string = price.find('p').get_text()
fprice = re.sub("[¥]+".decode("utf8"), "".decode("utf8"),string)
fprice = fprice[0:5]
print u'[短租房?jī)r(jià)格]', fprice.replace('\n','').strip()
#評(píng)分及評(píng)論人數(shù)
for score in name.find('ul'):
fscore = name.find('ul').get_text()
print u'[短租房評(píng)分/評(píng)論/居住人數(shù)]', fscore.replace('\n','').strip()
#網(wǎng)頁(yè)鏈接url
url_dzf = tag.find(attrs={"target":"_blank"})
urls = url_dzf.attrs['href']
print u'[網(wǎng)頁(yè)鏈接]', urls.replace('\n','').strip()
urlss = 'http://www.mayi.com' + urls + ''
print urlss
getInfo(urlss,fname,fprice,fscore,user_agent)
#主函數(shù)
if __name__ == '__main__':
i = 0
while i<33:
print u'頁(yè)碼', (i+1)
if(i==0):
url = 'http://www.mayi.com/guiyang/?map=no'
if(i>0):
num = i+2 #除了第一頁(yè)是空的,第二頁(yè)開(kāi)始按2順序遞增
url = 'http://www.mayi.com/guiyang/' + str(num) + '/?map=no'
gydzf(url)
i=i+1
c.close()輸出結(jié)果如下,存儲(chǔ)本地CSV文件:

上述內(nèi)容就是怎么在Python中通過(guò)設(shè)置Cookie解決網(wǎng)站攔截問(wèn)題,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
分享文章:怎么在Python中通過(guò)設(shè)置Cookie解決網(wǎng)站攔截問(wèn)題-創(chuàng)新互聯(lián)
轉(zhuǎn)載注明:http://chinadenli.net/article14/diidge.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、網(wǎng)站設(shè)計(jì)公司、品牌網(wǎng)站制作、動(dòng)態(tài)網(wǎng)站、品牌網(wǎng)站設(shè)計(jì)、電子商務(wù)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容