파충류 파이썬 지원 멀티 스레딩의 예

모든 사람들이 파이썬 지원 멀티 스레드 크롤러 인스턴스를 공유 할 오늘의 작은이, 좋은 참조 값을 가지고, 우리가 도와주고 싶어요. 팔로우 Xiaobian가 함께 모여 볼 수
ython는 다중 스레드 주로 스레드를 통해, 그리고 두 개의 모듈을 스레딩, 파이썬과 공유에이 논문 달성하기 위해 웹 크롤러를 멀티 스레드

일반적으로, 스레드의 사용은 두 가지 모드가 있는데, 하나의 기능이 수행되는 스레드 개체에 전달하는 기능을 실행하는 스레드를 생성한다. 또 다른 새로운 클래스를 생성 스레드로부터 직접 상속, 새로운 클래스 내부에 코드의 실행 스레드.

웹 크롤러 폭 우선 알고리즘을 달성하기 위해, 웹 크롤러, 멀티 스레딩 및 잠금 메커니즘의 사용을 멀티 스레드.

나는 당신에게 아이디어의 실현에 대한 간략한 소개를 줄 것이다 :

당신이 폭 통과를 다운로드하려면 웹 크롤러를 들어,이 있습니다 :

1. 첫 번째 페이지는 URL 주어진 입구에서 다운로드

다운로드 목록에 모든 새로운 웹 페이지 주소의 첫 번째 페이지에서 2. 추출

모든 새 페이지를 다운로드하는 주소 목록을 다운로드합니다

모든 새 페이지에 대한 웹 주소에서 다운로드하지 찾습니다 4. 업데이트 다운로드 목록

5.이 3 단계와 4 단계가 업데이트 될 때까지 다운로드 목록이 중지 될 때 빈 테이블

다음과 같이 파이썬 코드는 다음과 같습니다

#!/usr/bin/env python
#coding=utf-8
import threading
import urllib
import re
import time
g_mutex=threading.Condition()
g_pages=[] #从中解析所有url链接
g_queueURL=[] #等待爬取的url链接列表
g_existURL=[] #已经爬取过的url链接列表
g_failedURL=[] #下载失败的url链接列表
g_totalcount=0 #下载过的页面数
class Crawler:
 def __init__(self,crawlername,url,threadnum):
  self.crawlername=crawlername
  self.url=url
  self.threadnum=threadnum
  self.threadpool=[]
  self.logfile=file("log.txt",'w')
 def craw(self):
  global g_queueURL
  g_queueURL.append(url) 
  depth=0
  print self.crawlername+" 启动..."
  while(len(g_queueURL)!=0):
   depth+=1
   print 'Searching depth ',depth,'...\n\n'
   self.logfile.write("URL:"+g_queueURL[0]+"........")
   self.downloadAll()
   self.updateQueueURL()
   content='\n>>>Depth '+str(depth)+':\n'
   self.logfile.write(content)
   i=0
   while i<len(g_queueURL):
    content=str(g_totalcount+i)+'->'+g_queueURL[i]+'\n'
    self.logfile.write(content)
    i+=1
 def downloadAll(self):
  global g_queueURL
  global g_totalcount
  i=0
  while i<len(g_queueURL):
   j=0
   while j<self.threadnum and i+j < len(g_queueURL):
    g_totalcount+=1
    threadresult=self.download(g_queueURL[i+j],str(g_totalcount)+'.html',j)
    if threadresult!=None:
     print 'Thread started:',i+j,'--File number =',g_totalcount
    j+=1
   i+=j
   for thread in self.threadpool:
    thread.join(30)
   threadpool=[]
  g_queueURL=[]
 def download(self,url,filename,tid):
  crawthread=CrawlerThread(url,filename,tid)
  self.threadpool.append(crawthread)
  crawthread.start()
 def updateQueueURL(self):
  global g_queueURL
  global g_existURL
  newUrlList=[]
  for content in g_pages:
   newUrlList+=self.getUrl(content)
  g_queueURL=list(set(newUrlList)-set(g_existURL)) 
 def getUrl(self,content):
  reg=r'"(http://.+?)"'
  regob=re.compile(reg,re.DOTALL)
  urllist=regob.findall(content)
  return urllist
class CrawlerThread(threading.Thread):
 def __init__(self,url,filename,tid):
  threading.Thread.__init__(self)
  self.url=url
  self.filename=filename
  self.tid=tid
 def run(self):
  global g_mutex
  global g_failedURL
  global g_queueURL
  try:
   page=urllib.urlopen(self.url)
   html=page.read()
   fout=file(self.filename,'w')
   fout.write(html)
   fout.close()
  except Exception,e:
   g_mutex.acquire()
   g_existURL.append(self.url)
   g_failedURL.append(self.url)
   g_mutex.release()
   print 'Failed downloading and saving',self.url
   print e
   return None
  g_mutex.acquire()
  g_pages.append(html)
  g_existURL.append(self.url)
  g_mutex.release()
if __name__=="__main__":
 url=raw_input("请输入url入口:\n")
 threadnum=int(raw_input("设置线程数:"))
 crawlername="小小爬虫"
 crawler=Crawler(crawlername,url,threadnum)
 crawler.craw()

우리는 추천 사이트를 학습 파이썬 프로그램을 배우는 것입니다 얼마나 오래된보고! 기본 장고 파이썬 스크립트, 파충류, 데이터 마이닝, 프로그래밍 기술, 업무 경험뿐만 아니라에서 전투 작은 파이썬 파트너의 수석주의 연구는 제로 기반 정보 프로젝트를 마무리! 파이썬 프로그래머는이 기술을 설명하고, 방법은 작은 세부 사항에 관심을 지불 할 필요가 일부 학습 공유하고 정기적으로 하루
파이썬 파충류 예를 들어 모든 사람의 전체 내용을 공유 할 수있는 작은 일련의 멀티 스레딩이 지원 위, 나는 당신에게 참조를 제공하기 위해 희망

게시 51 개 원래 기사 · 원 찬양 17 ·은 30000 +를 볼

추천

출처blog.csdn.net/haoxun02/article/details/104419072