圖靈Python課堂
長沙圖靈教育于2001年開始進(jìn)入教育行業(yè),立足泛IT類職業(yè)教育,以打造高新技術(shù)人才為宗旨,專注于提供多層次、個性化的職業(yè)技能培訓(xùn)課程,為各行業(yè)培養(yǎng)技術(shù)開發(fā)、應(yīng)用和管理等崗位的中高端人才,致力于成為優(yōu)質(zhì)的職業(yè)教育內(nèi)容提供商。
01
Python優(yōu)勢
對于網(wǎng)絡(luò)爬蟲開發(fā)來說,Python有著無與倫比天然優(yōu)勢,這里從兩個方面對其優(yōu)勢進(jìn)行分析與講解。
1、抓取網(wǎng)頁本身的電商商品詳情API接口
相比其他靜態(tài)編程語言(如java、c#與c++)Python抓取網(wǎng)頁文檔的接口更簡潔,而對比其他動態(tài)腳本語言(如perl,shell)Python的urllib包提供了較為完整的訪問網(wǎng)頁文檔的API。
此外,抓取網(wǎng)頁有時候需要模擬瀏覽器的行為,很多網(wǎng)站對于生硬的爬蟲抓取都是封殺的。此時,需要模擬user agent的行為來構(gòu)造合適的請求(模擬用戶登錄、模擬session/cookie的存儲和設(shè)置)。在Python里都有非常優(yōu)秀的第三方包幫助搞定這些工作(如Requests,mechanize)。
2、網(wǎng)頁抓取后的處理
抓取的網(wǎng)頁通常需要處理,比如過濾html標(biāo)簽,提取文本等。Python的beautifulsoap提供了簡潔的文檔處理功能,能用極短的代碼完成大部分文檔的處理。
其實(shí)以上功能很多語言和工具都能做,但是用Python能夠干得最快,最干凈。
Life is short, you need python.
PS:python2.x和python3.x有很大不同,本文只討論python3.x的爬蟲實(shí)現(xiàn)方法。
02
爬蟲框架
URL管理器:管理待爬取的url集合和已爬取的url集合,傳送待爬取的url給網(wǎng)頁下載器。
網(wǎng)頁下載器(urllib):爬取url對應(yīng)的網(wǎng)頁,存儲成字符串,傳送給網(wǎng)頁解析器。
網(wǎng)頁解析器(BeautifulSoup):解析出有價(jià)值的數(shù)據(jù),存儲下來,同時補(bǔ)充url到URL管理器。
03
URL管理器
基本功能
-
添加新的url到待爬取url集合中。
-
判斷待添加的url是否在容器中(包括待爬取url集合和已爬取url集合)。
-
獲取待爬取的url。
-
判斷是否有待爬取的url。
-
將爬取完成的url從待爬取url集合移動到已爬取url集合。
存儲方式
1、內(nèi)存(python內(nèi)存)
待爬取url集合:set()
已爬取url集合:set()
2、關(guān)系數(shù)據(jù)庫(mysql)
urls(url, is_crawled)
3、緩存(redis)
待爬取url集合:set
已爬取url集合:set
大型互聯(lián)網(wǎng)公司,由于緩存數(shù)據(jù)庫的性能高,所以一般把url存儲在緩存數(shù)據(jù)庫中。小型公司,一般把url存儲在內(nèi)存中,要永久存儲,則存儲到關(guān)系數(shù)據(jù)庫中。
05
網(wǎng)頁下載器urllib
將url對應(yīng)的網(wǎng)頁下載到本地,存儲成一個文件或字符串。
基本方法
新建baidu.py,內(nèi)容如下:
import?urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
buff = response.read()
html = buff.decode("utf8")print(html)
命令行中執(zhí)行python baidu.py,則可以打印出獲取到的頁面。
構(gòu)造Request
上面的代碼,可以修改為:
import?urllib.request
request = urllib.request.Request('http://www.baidu.com')
response = urllib.request.urlopen(request)
buff = response.read()
html = buff.decode("utf8")
print(html)
攜帶參數(shù)
新建baidu2.py,內(nèi)容如下:
import?urllib.requestimport?urllib.parse
url = 'http://www.baidu.com'values = {'name': 'voidking','language': 'Python'}data = urllib.parse.urlencode(values).encode(encoding='utf-8',errors='ignore')
headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0' }
request = urllib.request.Request(url=url, data=data,headers=headers,method='GET')
response = urllib.request.urlopen(request)
buff = response.read()
html = buff.decode("utf8")
print(html)
使用Fiddler監(jiān)聽數(shù)據(jù)
要查看請求是否真的攜帶了參數(shù),需使用fiddler。
添加處理器
import urllib.request
import http.cookiejar# 創(chuàng)建cookie容器cj = http.cookiejar.CookieJar()# 創(chuàng)建openeropener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))# 給urllib.request安裝openerurllib.request.install_opener(opener)# 請求request = urllib.request.Request('http://www.baidu.com/')
response = urllib.request.urlopen(request)
buff = response.read()
html = buff.decode("utf8")
print(html)
print(cj)
06
網(wǎng)頁解析器(BeautifulSoup)
從網(wǎng)頁中提取出有價(jià)值的數(shù)據(jù)和新的url列表。
解析器選擇
為了實(shí)現(xiàn)解析器,可以選擇使用正則表達(dá)式、html.parser、BeautifulSoup、lxml等,這里選擇BeautifulSoup。其中,正則表達(dá)式基于模糊匹配,而另外三種則是基于DOM結(jié)構(gòu)化解析。
BeautifulSoup安裝測試
1、安裝,在命令行下執(zhí)行pip install beautifulsoup4。
2、測試
import bs4print(bs4)
基本用法
1、創(chuàng)建BeautifulSoup對象
import bs4
from bs4 import BeautifulSoup
# 根據(jù)html網(wǎng)頁字符串創(chuàng)建BeautifulSoup對象
html_doc = """<html><head><title>The Dormouse's story</title></head><body><p class="title"><b>The Dormouse's story</b></p><p class="story">Once upon a time there were three little sisters; and their names were<a class="sister" id="link1">Elsie</a>,<a class="sister" id="link2">Lacie</a> and<a class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p><p class="story">...</p>"""
soup = BeautifulSoup(html_doc)
print(soup.prettify())
2、訪問節(jié)點(diǎn)
print(soup.title)
print(soup.title.name)
print(soup.title.string)
print(soup.title.parent.name)
print(soup.p)
print(soup.p['class'])
3、指定tag、class或id
print(soup.find_all('a'))
print(soup.find('a'))
print(soup.find(class_='title'))
print(soup.find(id="link3"))
print(soup.find('p',class_='title'))
4、從文檔中找到所有<a>標(biāo)簽的鏈接
for link in soup.find_all('a'):
? ?print(link.get('href'))
出現(xiàn)了警告,根據(jù)提示,在創(chuàng)建BeautifulSoup對象時,指定解析器即可。
soup = BeautifulSoup(html_doc,'html.parser')
5、從文檔中獲取所有文字內(nèi)容文章來源:http://www.zghlxwxcb.cn/news/detail-609570.html
print(soup.get_text())
6、正則匹配文章來源地址http://www.zghlxwxcb.cn/news/detail-609570.html
link_node = soup.find('a',href=re.compile(r"til"))
print(link_node)
到了這里,關(guān)于Python電商爬蟲保姆級入門教程(純新手向)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!