python爬蟲實(shí)例講解
1.爬取網(wǎng)頁(yè)
通過導(dǎo)入request,re庫(kù),首先編寫一個(gè)將淘寶商品頁(yè)爬取的函數(shù),此時(shí)一個(gè)注意點(diǎn)是要將自己頭部的user agent偽裝成瀏覽器(淘寶會(huì)拒絕爬蟲請(qǐng)求),并且采用設(shè)計(jì)好的cookie,放入request.get的參數(shù)中,返回網(wǎng)頁(yè)信息。`
import requests
import re
def get_html_text(url):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} #爬蟲頭部偽裝成瀏覽器頭部,方便get到url
try:
coo = 't=85db5e7cb0133f23f29f98c7d6955615; cna=3uklFEhvXUoCAd9H6ovaVLTG; isg=BM3NGT0Oqmp6Mg4qfcGPnvDY3-pNqzF2joji8w9SGWTYBu241_taTS6UdFrF3Rk0; miid=983575671563913813; thw=cn; um=535523100CBE37C36EEFF761CFAC96BC4CD04CD48E6631C3112393F438E181DF6B34171FDA66B2C2CD43AD3E795C914C34A100CE538767508DAD6914FD9E61CE; _cc_=W5iHLLyFfA%3D%3D; tg=0; enc=oRI1V9aX5p%2BnPbULesXvnR%2BUwIh9CHIuErw0qljnmbKe0Ecu1Gxwa4C4%2FzONeGVH9StU4Isw64KTx9EHQEhI2g%3D%3D; hng=CN%7Czh-CN%7CCNY%7C156; mt=ci=0_0; hibext_instdsigdipv2=1; JSESSIONID=EC33B48CDDBA7F11577AA9FEB44F0DF3'
cookies = {}
for line in coo.split(';'): # 瀏覽器偽裝 同樣是為了成功爬取頁(yè)面
name, value = line.strip().split('=', 1)
cookies[name] = value
r = requests.get(url, cookies=cookies, headers=headers, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ''
2. 正確獲得我們需要的信息(爬蟲關(guān)鍵)
我們通過觀察網(wǎng)頁(yè)源代碼找到商品與價(jià)格位于view price和raw title之后,利用導(dǎo)入的re庫(kù)我們使用正則表達(dá)式表示出我們想要爬取的部分,再用split函數(shù)去掉列表前面的定位詞(view price,raw title),并用appen函數(shù)講列表兩個(gè)元素商品和價(jià)格封裝好。
def parsePage(ilt,html):
try:
plt=re.findall(r'\"view_price\"\:\"[\d\.]*\"',html) #觀察源代碼找到商品名稱以及價(jià)格所在地,設(shè)計(jì)出正則表達(dá)式提取出商品名稱以及價(jià)格。
tlt=re.findall(r'\"raw_title\"\:\".*?\"',html)
for i in range(len(plt)):
price=eval(plt[i].split(":")[1])
title=eval(tlt[i].split(":")[1])
ilt.append([price,title])
except:
print("")
3.調(diào)用輸出函數(shù)以及編寫主函數(shù)
輸出時(shí)候我們先設(shè)計(jì)個(gè)美觀的表格格式tplt,然后以他為format進(jìn)行輸出,通過count給他加上序號(hào)。主函數(shù)很簡(jiǎn)單,調(diào)用上面編寫的函數(shù)即可。
注意:url翻頁(yè)功能的實(shí)現(xiàn)就是觀察淘寶翻頁(yè)時(shí)候url的變化來編寫翻頁(yè)的小循環(huán),depth代表翻的頁(yè)數(shù),44是淘寶每個(gè)頁(yè)面呈現(xiàn)的商品數(shù)量,第一頁(yè)s=0,第二頁(yè)s=44,以此類推,這里僅爬了前兩頁(yè)。
def printGoodsList(ilt):
tplt = "{:4}\t{:8}\t{:16}" #設(shè)計(jì)表格長(zhǎng)度
print(tplt.format("序號(hào)","價(jià)格","商品名稱"))
count=0
for g in ilt:
count=count+1
print(tplt.format(count,g[0],g[1]))
print("")
def main():
goods="書包"
depth=2
start_url="https://s.taobao.com/search?q="+goods
info_list = []
for i in range(depth):
try:
url = start_url + '&s=' + str(44 * i) # 44是淘寶每個(gè)頁(yè)面呈現(xiàn)的寶貝數(shù)量
html = get_html_text(url)
parsePage(info_list, html)
except:
continue
printGoodsList(info_list)
main()
4.輸出結(jié)果

image.png