本文實例講述了Python實現多線程抓取網頁功能。分享給大家供大家參考,具體如下:
最近,一直在做網絡爬蟲相關的東西。 看了一下開源C++寫的larbin爬蟲,仔細閱讀了里面的設計思想和一些關鍵技術的實現。
1、larbin的URL去重用的很高效的bloom filter算法;
2、DNS處理,使用的adns異步的開源組件;
3、對于url隊列的處理,則是用部分緩存到內存,部分寫入文件的策略。
4、larbin對文件的相關操作做了很多工作
5、在larbin里有連接池,通過創建套接字,向目標站點發送HTTP協議中GET方法,獲取內容,再解析header之類的東西
6、大量描述字,通過poll方法進行I/O復用,很高效
7、larbin可配置性很強
8、作者所使用的大量數據結構都是自己從最底層寫起的,基本沒用STL之類的東西
......
還有很多,以后有時間在好好寫篇文章,總結下。
這兩天,用python寫了個多線程下載頁面的程序,對于I/O密集的應用而言,多線程顯然是個很好的解決方案。剛剛寫過的線程池,也正好可以利用上了。其實用python爬取頁面非常簡單,有個urllib2的模塊,使用起來很方便,基本兩三行代碼就可以搞定。雖然使用第三方模塊,可以很方便的解決問題,但是對個人的技術積累而言沒有什么好處,因為關鍵的算法都是別人實現的,而不是你自己實現的,很多細節的東西,你根本就無法了解。 我們做技術的,不能一味的只是用別人寫好的模塊或是api,要自己動手實現,才能讓自己學習得更多。
我決定從socket寫起,也是去封裝GET協議,解析header,而且還可以把DNS的解析過程單獨處理,例如DNS緩存一下,所以這樣自己寫的話,可控性更強,更有利于擴展。對于timeout的處理,我用的全局的5秒鐘的超時處理,對于重定位(301or302)的處理是,最多重定位3次,因為之前測試過程中,發現很多站點的重定位又定位到自己,這樣就無限循環了,所以設置了上限。具體原理,比較簡單,直接看代碼就好了。
自己寫完之后,與urllib2進行了下性能對比,自己寫的效率還是比較高的,而且urllib2的錯誤率稍高一些,不知道為什么。網上有人說urllib2在多線程背景下有些小問題,具體我也不是特別清楚。
先貼代碼:
fetchPage.py 使用Http協議的Get方法,進行頁面下載,并存儲為文件
'''Created on 2012-3-13Get Page using GET methodDefault using HTTP Protocol , http port 80@author: xiaojay'''import socketimport statisticsimport datetimeimport threadingsocket.setdefaulttimeout(statistics.timeout)class Error404(Exception):  '''Can not find the page.'''  passclass ErrorOther(Exception):  '''Some other exception'''  def __init__(self,code):    #print 'Code :',code    passclass ErrorTryTooManyTimes(Exception):  '''try too many times'''  passdef 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+filenamedef 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 edef PrintDNSCache():  '''print DNS dict'''  n = 1  for hostname in statistics.DNSCache.keys():    print n,'/t',hostname, '/t',statistics.DNSCache[hostname]    n+=1def 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", urlif __name__=='__main__':  print 'Get Page using GET method'            
新聞熱點
疑難解答