
Python實(shí)現(xiàn)多線(xiàn)程抓取網(wǎng)頁(yè)功能實(shí)例詳解
本文實(shí)例講述了Python實(shí)現(xiàn)多線(xiàn)程抓取網(wǎng)頁(yè)功能。分享給大家供大家參考,具體如下:
最近,一直在做網(wǎng)絡(luò)爬蟲(chóng)相關(guān)的東西。 看了一下開(kāi)源C++寫(xiě)的larbin爬蟲(chóng),仔細(xì)閱讀了里面的設(shè)計(jì)思想和一些關(guān)鍵技術(shù)的實(shí)現(xiàn)。
1、larbin的URL去重用的很高效的bloom filter算法;
2、DNS處理,使用的adns異步的開(kāi)源組件;
3、對(duì)于url隊(duì)列的處理,則是用部分緩存到內(nèi)存,部分寫(xiě)入文件的策略。
4、larbin對(duì)文件的相關(guān)操作做了很多工作
5、在larbin里有連接池,通過(guò)創(chuàng)建套接字,向目標(biāo)站點(diǎn)發(fā)送HTTP協(xié)議中GET方法,獲取內(nèi)容,再解析header之類(lèi)的東西
6、大量描述字,通過(guò)poll方法進(jìn)行I/O復(fù)用,很高效
7、larbin可配置性很強(qiáng)
8、作者所使用的大量數(shù)據(jù)結(jié)構(gòu)都是自己從最底層寫(xiě)起的,基本沒(méi)用STL之類(lèi)的東西
......
還有很多,以后有時(shí)間在好好寫(xiě)篇文章,總結(jié)下。
這兩天,用python寫(xiě)了個(gè)多線(xiàn)程下載頁(yè)面的程序,對(duì)于I/O密集的應(yīng)用而言,多線(xiàn)程顯然是個(gè)很好的解決方案。剛剛寫(xiě)過(guò)的線(xiàn)程池,也正好可以利用上了。其實(shí)用python爬取頁(yè)面非常簡(jiǎn)單,有個(gè)urllib2的模塊,使用起來(lái)很方便,基本兩三行代碼就可以搞定。雖然使用第三方模塊,可以很方便的解決問(wèn)題,但是對(duì)個(gè)人的技術(shù)積累而言沒(méi)有什么好處,因?yàn)殛P(guān)鍵的算法都是別人實(shí)現(xiàn)的,而不是你自己實(shí)現(xiàn)的,很多細(xì)節(jié)的東西,你根本就無(wú)法了解。 我們做技術(shù)的,不能一味的只是用別人寫(xiě)好的模塊或是api,要自己動(dòng)手實(shí)現(xiàn),才能讓自己學(xué)習(xí)得更多。
我決定從socket寫(xiě)起,也是去封裝GET協(xié)議,解析header,而且還可以把DNS的解析過(guò)程單獨(dú)處理,例如DNS緩存一下,所以這樣自己寫(xiě)的話(huà),可控性更強(qiáng),更有利于擴(kuò)展。對(duì)于timeout的處理,我用的全局的5秒鐘的超時(shí)處理,對(duì)于重定位(301or302)的處理是,最多重定位3次,因?yàn)橹皽y(cè)試過(guò)程中,發(fā)現(xiàn)很多站點(diǎn)的重定位又定位到自己,這樣就無(wú)限循環(huán)了,所以設(shè)置了上限。具體原理,比較簡(jiǎn)單,直接看代碼就好了。
自己寫(xiě)完之后,與urllib2進(jìn)行了下性能對(duì)比,自己寫(xiě)的效率還是比較高的,而且urllib2的錯(cuò)誤率稍高一些,不知道為什么。網(wǎng)上有人說(shuō)urllib2在多線(xiàn)程背景下有些小問(wèn)題,具體我也不是特別清楚。
先貼代碼:
fetchPage.py 使用Http協(xié)議的Get方法,進(jìn)行頁(yè)面下載,并存儲(chǔ)為文件
'''
Created on 2012-3-13
Get Page using GET method
Default using HTTP Protocol , http port 80
@author: xiaojay
'''
import socket
import statistics
import datetime
import threading
socket.setdefaulttimeout(statistics.timeout)
class Error404(Exception):
'''Can not find the page.'''
pass
class ErrorOther(Exception):
'''Some other exception'''
def __init__(self,code):
#print 'Code :',code
pass
class ErrorTryTooManyTimes(Exception):
'''try too many times'''
pass
def downPage(hostname ,filename , trytimes=0):
try :
#To avoid too many tries .Try times can not be more than max_try_times
if trytimes >= statistics.max_try_times :
raise ErrorTryTooManyTimes
except ErrorTryTooManyTimes :
return statistics.RESULTTRYTOOMANY,hostname+filename
try:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#DNS cache
if statistics.DNSCache.has_key(hostname):
addr = statistics.DNSCache[hostname]
else:
addr = socket.gethostbyname(hostname)
statistics.DNSCache[hostname] = addr
#connect to http server ,default port 80
s.connect((addr,80))
msg = 'GET '+filename+' HTTP/1.0\r\n'
msg += 'Host: '+hostname+'\r\n'
msg += 'User-Agent:xiaojay\r\n\r\n'
code = ''
f = None
s.sendall(msg)
first = True
while True:
msg = s.recv(40960)
if not len(msg):
if f!=None:
f.flush()
f.close()
break
# Head information must be in the first recv buffer
if first:
first = False
headpos = msg.index("\r\n\r\n")
code,other = dealwithHead(msg[:headpos])
if code=='200':
#statistics.fetched_url += 1
f = open('pages/'+str(abs(hash(hostname+filename))),'w')
f.writelines(msg[headpos+4:])
elif code=='301' or code=='302':
#if code is 301 or 302 , try down again using redirect location
if other.startswith("http") :
hname, fname = parse(other)
downPage(hname,fname,trytimes+1)#try again
else :
downPage(hostname,other,trytimes+1)
elif code=='404':
raise Error404
else :
raise ErrorOther(code)
else:
if f!=None :f.writelines(msg)
s.shutdown(socket.SHUT_RDWR)
s.close()
return statistics.RESULTFETCHED,hostname+filename
except Error404 :
return statistics.RESULTCANNOTFIND,hostname+filename
except ErrorOther:
return statistics.RESULTOTHER,hostname+filename
except socket.timeout:
return statistics.RESULTTIMEOUT,hostname+filename
except Exception, e:
return statistics.RESULTOTHER,hostname+filename
def dealwithHead(head):
'''deal with HTTP HEAD'''
lines = head.splitlines()
fstline = lines[0]
code =fstline.split()[1]
if code == '404' : return (code,None)
if code == '200' : return (code,None)
if code == '301' or code == '302' :
for line in lines[1:]:
p = line.index(':')
key = line[:p]
if key=='Location' :
return (code,line[p+2:])
return (code,None)
def parse(url):
'''Parse a url to hostname+filename'''
try:
u = url.strip().strip('\n').strip('\r').strip('\t')
if u.startswith('http://') :
u = u[7:]
elif u.startswith('https://'):
u = u[8:]
if u.find(':80')>0 :
p = u.index(':80')
p2 = p + 3
else:
if u.find('/')>0:
p = u.index('/')
p2 = p
else:
p = len(u)
p2 = -1
hostname = u[:p]
if p2>0 :
filename = u[p2:]
else : filename = '/'
return hostname, filename
except Exception ,e:
print "Parse wrong : " , url
print e
def PrintDNSCache():
'''print DNS dict'''
n = 1
for hostname in statistics.DNSCache.keys():
print n,'\t',hostname, '\t',statistics.DNSCache[hostname]
n+=1
def dealwithResult(res,url):
'''Deal with the result of downPage'''
statistics.total_url+=1
if res==statistics.RESULTFETCHED :
statistics.fetched_url+=1
print statistics.total_url , '\t fetched :', url
if res==statistics.RESULTCANNOTFIND :
statistics.failed_url+=1
print "Error 404 at : ", url
if res==statistics.RESULTOTHER :
statistics.other_url +=1
print "Error Undefined at : ", url
if res==statistics.RESULTTIMEOUT :
statistics.timeout_url +=1
print "Timeout ",url
if res==statistics.RESULTTRYTOOMANY:
statistics.trytoomany_url+=1
print e ,"Try too many times at", url
if __name__=='__main__':
print 'Get Page using GET method'
下面,我將利用上一篇的線(xiàn)程池作為輔助,實(shí)現(xiàn)多線(xiàn)程下的并行爬取,并用上面自己寫(xiě)的下載頁(yè)面的方法和urllib2進(jìn)行一下性能對(duì)比。
'''
Created on 2012-3-16
@author: xiaojay
'''
import fetchPage
import threadpool
import datetime
import statistics
import urllib2
'''one thread'''
def usingOneThread(limit):
urlset = open("input.txt","r")
start = datetime.datetime.now()
for u in urlset:
if limit <= 0 : break
limit-=1
hostname , filename = parse(u)
res= fetchPage.downPage(hostname,filename,0)
fetchPage.dealwithResult(res)
end = datetime.datetime.now()
print "Start at :\t" , start
print "End at :\t" , end
print "Total Cost :\t" , end - start
print 'Total fetched :', statistics.fetched_url
'''threadpoll and GET method'''
def callbackfunc(request,result):
fetchPage.dealwithResult(result[0],result[1])
def usingThreadpool(limit,num_thread):
urlset = open("input.txt","r")
start = datetime.datetime.now()
main = threadpool.ThreadPool(num_thread)
for url in urlset :
try :
hostname , filename = fetchPage.parse(url)
req = threadpool.WorkRequest(fetchPage.downPage,args=[hostname,filename],kwds={},callback=callbackfunc)
main.putRequest(req)
except Exception:
print Exception.message
while True:
try:
main.poll()
if statistics.total_url >= limit : break
except threadpool.NoResultsPending:
print "no pending results"
break
except Exception ,e:
print e
end = datetime.datetime.now()
print "Start at :\t" , start
print "End at :\t" , end
print "Total Cost :\t" , end - start
print 'Total url :',statistics.total_url
print 'Total fetched :', statistics.fetched_url
print 'Lost url :', statistics.total_url - statistics.fetched_url
print 'Error 404 :' ,statistics.failed_url
print 'Error timeout :',statistics.timeout_url
print 'Error Try too many times ' ,statistics.trytoomany_url
print 'Error Other faults ',statistics.other_url
main.stop()
'''threadpool and urllib2 '''
def downPageUsingUrlib2(url):
try:
req = urllib2.Request(url)
fd = urllib2.urlopen(req)
f = open("pages3/"+str(abs(hash(url))),'w')
f.write(fd.read())
f.flush()
f.close()
return url ,'success'
except Exception:
return url , None
def writeFile(request,result):
statistics.total_url += 1
if result[1]!=None :
statistics.fetched_url += 1
print statistics.total_url,'\tfetched :', result[0],
else:
statistics.failed_url += 1
print statistics.total_url,'\tLost :',result[0],
def usingThreadpoolUrllib2(limit,num_thread):
urlset = open("input.txt","r")
start = datetime.datetime.now()
main = threadpool.ThreadPool(num_thread)
for url in urlset :
try :
req = threadpool.WorkRequest(downPageUsingUrlib2,args=[url],kwds={},callback=writeFile)
main.putRequest(req)
except Exception ,e:
print e
while True:
try:
main.poll()
if statistics.total_url >= limit : break
except threadpool.NoResultsPending:
print "no pending results"
break
except Exception ,e:
print e
end = datetime.datetime.now()
print "Start at :\t" , start
print "End at :\t" , end
print "Total Cost :\t" , end - start
print 'Total url :',statistics.total_url
print 'Total fetched :', statistics.fetched_url
print 'Lost url :', statistics.total_url - statistics.fetched_url
main.stop()
if __name__ =='__main__':
'''too slow'''
#usingOneThread(100)
'''use Get method'''
#usingThreadpool(3000,50)
'''use urllib2'''
usingThreadpoolUrllib2(3000,50)
實(shí)驗(yàn)分析:
實(shí)驗(yàn)數(shù)據(jù):larbin抓取下來(lái)的3000條url,經(jīng)過(guò)Mercator隊(duì)列模型(我用c++實(shí)現(xiàn)的,以后有機(jī)會(huì)發(fā)個(gè)blog)處理后的url集合,具有隨機(jī)和代表性。使用50個(gè)線(xiàn)程的線(xiàn)程池。
實(shí)驗(yàn)環(huán)境:ubuntu10.04,網(wǎng)絡(luò)較好,python2.6
存儲(chǔ):小文件,每個(gè)頁(yè)面,一個(gè)文件進(jìn)行存儲(chǔ)
PS:由于學(xué)校上網(wǎng)是按流量收費(fèi)的,做網(wǎng)絡(luò)爬蟲(chóng),灰常費(fèi)流量?。。?!過(guò)幾天,可能會(huì)做個(gè)大規(guī)模url下載的實(shí)驗(yàn),用個(gè)幾十萬(wàn)的url試試。
實(shí)驗(yàn)結(jié)果:
使用urllib2,usingThreadpoolUrllib2(3000,50)
Start at : 2012-03-16 22:18:20.956054
End at : 2012-03-16 22:22:15.203018
Total Cost : 0:03:54.246964
Total url : 3001
Total fetched : 2442
Lost url : 559
下載頁(yè)面的物理存儲(chǔ)大?。?4088kb
使用自己的getPageUsingGet ,usingThreadpool(3000,50)
Start at : 2012-03-16 22:23:40.206730
End at : 2012-03-16 22:26:26.843563
Total Cost : 0:02:46.636833
Total url : 3002
Total fetched : 2484
Lost url : 518
Error 404 : 94
Error timeout : 312
Error Try too many times 0
Error Other faults 112
下載頁(yè)面的物理存儲(chǔ)大?。?7168kb
小結(jié):自己寫(xiě)的下載頁(yè)面程序,效率還是很不錯(cuò)的,而且丟失的頁(yè)面也較少。但其實(shí)自己考慮一下,還是有很多地方可以?xún)?yōu)化的,比如文件過(guò)于分散,過(guò)多的小文件創(chuàng)建和釋放定會(huì)產(chǎn)生不小的性能開(kāi)銷(xiāo),而且程序里用的是hash命名,也會(huì)產(chǎn)生很多的計(jì)算,如果有好的策略,其實(shí)這些開(kāi)銷(xiāo)都是可以省略的。另外DNS,也可以不使用python自帶的DNS解析,因?yàn)槟J(rèn)的DNS解析都是同步的操作,而DNS解析一般比較耗時(shí),可以采取多線(xiàn)程的異步的方式進(jìn)行,再加以適當(dāng)?shù)腄NS緩存很大程度上可以提高效率。不僅如此,在實(shí)際的頁(yè)面抓取過(guò)程中,會(huì)有大量的url ,不可能一次性把它們存入內(nèi)存,而應(yīng)該按照一定的策略或是算法進(jìn)行合理的分配。 總之,采集頁(yè)面要做的東西以及可以?xún)?yōu)化的東西,還有很多很多。
數(shù)據(jù)分析咨詢(xún)請(qǐng)掃描二維碼
若不方便掃碼,搜微信號(hào):CDAshujufenxi
LSTM 模型輸入長(zhǎng)度選擇技巧:提升序列建模效能的關(guān)鍵? 在循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)家族中,長(zhǎng)短期記憶網(wǎng)絡(luò)(LSTM)憑借其解決長(zhǎng)序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報(bào)考條件詳解與準(zhǔn)備指南? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代浪潮下,CDA 數(shù)據(jù)分析師認(rèn)證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計(jì)的實(shí)用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強(qiáng)大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶(hù) ...
2025-07-11尊敬的考生: 您好! 我們誠(chéng)摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實(shí)施重大更新。 此次更新旨在確保認(rèn) ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務(wù)的價(jià)值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡(jiǎn)稱(chēng) BI)深度融合的時(shí)代,BI ...
2025-07-10SQL 在預(yù)測(cè)分析中的應(yīng)用:從數(shù)據(jù)查詢(xún)到趨勢(shì)預(yù)判? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代,預(yù)測(cè)分析作為挖掘數(shù)據(jù)潛在價(jià)值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢(xún)結(jié)束后:分析師的收尾工作與價(jià)值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢(xún)結(jié)束)并非工作的終點(diǎn),而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報(bào)考到取證的全攻略? 在數(shù)字經(jīng)濟(jì)蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭(zhēng)搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢(shì)性檢驗(yàn):捕捉數(shù)據(jù)背后的時(shí)間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢(shì)性檢驗(yàn)如同一位耐心的偵探,專(zhuān)注于從單 ...
2025-07-09year_month數(shù)據(jù)類(lèi)型:時(shí)間維度的精準(zhǔn)切片? ? 在數(shù)據(jù)的世界里,時(shí)間是最不可或缺的維度之一,而year_month數(shù)據(jù)類(lèi)型就像一把精準(zhǔn) ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應(yīng)用與實(shí)戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認(rèn)證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗(yàn):數(shù)據(jù)趨勢(shì)與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領(lǐng)域中,準(zhǔn)確捕捉數(shù)據(jù)的趨勢(shì)變化以及識(shí)別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認(rèn)證作為國(guó)內(nèi)權(quán)威的數(shù)據(jù)分析能力認(rèn)證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應(yīng)對(duì)策略? 長(zhǎng)短期記憶網(wǎng)絡(luò)(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的一種變體,憑借獨(dú)特的門(mén)控機(jī)制,在 ...
2025-07-07統(tǒng)計(jì)學(xué)方法在市場(chǎng)調(diào)研數(shù)據(jù)中的深度應(yīng)用? 市場(chǎng)調(diào)研是企業(yè)洞察市場(chǎng)動(dòng)態(tài)、了解消費(fèi)者需求的重要途徑,而統(tǒng)計(jì)學(xué)方法則是市場(chǎng)調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書(shū)考試全攻略? 在數(shù)字化浪潮席卷全球的當(dāng)下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動(dòng)力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專(zhuān)業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關(guān)鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準(zhǔn)確性的基礎(chǔ) ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動(dòng)力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開(kāi)啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價(jià)值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03