前言
Python非常適合用來開發(fā)網(wǎng)頁爬蟲琢歇,理由如下:
1兰怠、抓取網(wǎng)頁本身的接口
相比與其他靜態(tài)編程語言,如java李茫,c#揭保,c++,python抓取網(wǎng)頁文檔的接口更簡潔魄宏;相比其他動(dòng)態(tài)腳本語言秸侣,如perl,shell宠互,python的urllib包提供了較為完整的訪問網(wǎng)頁文檔的API味榛。(當(dāng)然ruby也是很好的選擇)
此外,抓取網(wǎng)頁有時(shí)候需要模擬瀏覽器的行為予跌,很多網(wǎng)站對(duì)于生硬的爬蟲抓取都是封殺的搏色。這是我們需要模擬user agent的行為構(gòu)造合適的請(qǐng)求,譬如模擬用戶登陸券册、模擬session/cookie的存儲(chǔ)和設(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)方法跨细。
爬蟲架構(gòu)
架構(gòu)組成
URL管理器:管理待爬取的url集合和已爬取的url集合,傳送待爬取的url給網(wǎng)頁下載器河质。
網(wǎng)頁下載器(urllib):爬取url對(duì)應(yīng)的網(wǎng)頁冀惭,存儲(chǔ)成字符串,傳送給網(wǎng)頁解析器掀鹅。
網(wǎng)頁解析器(BeautifulSoup):解析出有價(jià)值的數(shù)據(jù)散休,存儲(chǔ)下來,同時(shí)補(bǔ)充url到URL管理器乐尊。
運(yùn)行流程
URL管理器
基本功能
?添加新的url到待爬取url集合中戚丸。
?判斷待添加的url是否在容器中(包括待爬取url集合和已爬取url集合)。
?獲取待爬取的url扔嵌。
?判斷是否有待爬取的url限府。
?將爬取完成的url從待爬取url集合移動(dòng)到已爬取url集合。
存儲(chǔ)方式
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存儲(chǔ)在緩存數(shù)據(jù)庫中。小型公司嵌洼,一般把url存儲(chǔ)在內(nèi)存中案疲,如果想要永久存儲(chǔ),則存儲(chǔ)到關(guān)系數(shù)據(jù)庫中麻养。
網(wǎng)頁下載器(urllib)
將url對(duì)應(yīng)的網(wǎng)頁下載到本地络拌,存儲(chǔ)成一個(gè)文件或字符串。
基本方法
新建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.request
import 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ù)
我們想要查看一下,我們的請(qǐng)求是否真的攜帶了參數(shù)车要,所以需要使用fiddler允粤。
打開fiddler之后,卻意外發(fā)現(xiàn),上面的代碼會(huì)報(bào)錯(cuò)504类垫,無論是baidu.py還是baidu2.py司光。
雖然python有報(bào)錯(cuò),但是在fiddler中悉患,我們可以看到請(qǐng)求信息残家,確實(shí)攜帶了參數(shù)。
然而驰怎,然而,然而二打。县忌。。神轉(zhuǎn)折出現(xiàn)了<绦АV⑿印!
當(dāng)我把url換成
http://www.csdn.net/
后瑞信,請(qǐng)求成功厉颤!沒錯(cuò),就是在網(wǎng)址后面多加了一個(gè)斜杠/
同理凡简,把http://www.baidu.com
改成http://www.baidu.com/
逼友,請(qǐng)求也成功了!神奇3由V钠颉!
添加處理器
import urllib.request
import http.cookiejar
# 創(chuàng)建cookie容器
cj = http.cookiejar.CookieJar()
# 創(chuàng)建opener
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
# 給urllib.request安裝opener
urllib.request.install_opener(opener)
# 請(qǐng)求
request = urllib.request.Request('http://www.baidu.com/')
response = urllib.request.urlopen(request)
buff = response.read()
html = buff.decode("utf8")
print(html)
print(cj)
網(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 bs4
print(bs4)
使用說明
基本用法
1驻售、創(chuàng)建BeautifulSoup對(duì)象
import bs4
from bs4 import BeautifulSoup
# 根據(jù)html網(wǎng)頁字符串創(chuàng)建BeautifulSoup對(duì)象
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對(duì)象時(shí),指定解析器即可栏笆。
soup = BeautifulSoup(html_doc,'html.parser')
5类腮、從文檔中獲取所有文字內(nèi)容
print(soup.get_text())
6、正則匹配
link_node = soup.find('a',href=re.compile(r"til")) print(link_node)
后記
python爬蟲基礎(chǔ)知識(shí)蛉加,至此足夠蚜枢,接下來,在實(shí)戰(zhàn)中學(xué)習(xí)更高級(jí)的知識(shí)针饥。