python支持多线程的爬虫实例


Posted in Python onDecember 21, 2019

python是支持多线程的, 主要是通过thread和threading这两个模块来实现的,本文主要给大家分享python实现多线程网页爬虫

一般来说,使用线程有两种模式, 一种是创建线程要执行的函数, 把这个函数传递进Thread对象里,让它来执行. 另一种是直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的class里。

实现多线程网页爬虫,采用了多线程和锁机制,实现了广度优先算法的网页爬虫。

先给大家简单介绍下我的实现思路:

对于一个网络爬虫,如果要按广度遍历的方式下载,它是这样的:

1.从给定的入口网址把第一个网页下载下来

2.从第一个网页中提取出所有新的网页地址,放入下载列表中

3.按下载列表中的地址,下载所有新的网页

4.从所有新的网页中找出没有下载过的网页地址,更新下载列表

5.重复3、4两步,直到更新后的下载列表为空表时停止

python代码如下:

#!/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()

以上这篇python支持多线程的爬虫实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python的Django框架中的Context使用
Jul 15 Python
在类Unix系统上开始Python3编程入门
Aug 20 Python
Python使用filetype精确判断文件类型
Jul 02 Python
python3.4控制用户输入与输出的方法
Oct 17 Python
Django组件之cookie与session的使用方法
Jan 10 Python
python实现QQ邮箱/163邮箱的邮件发送
Jan 22 Python
Django网络框架之创建虚拟开发环境操作示例
Jun 06 Python
python pytest进阶之conftest.py详解
Jun 27 Python
Python中那些 Pythonic的写法详解
Jul 02 Python
Python 批量刷博客园访问量脚本过程解析
Aug 30 Python
如何用OpenCV -python3实现视频物体追踪
Dec 04 Python
Python批量启动多线程代码实例
Feb 18 Python
Python 实现try重新执行
Dec 21 #Python
在python shell中运行python文件的实现
Dec 21 #Python
Python 脚本的三种执行方式小结
Dec 21 #Python
python带参数打包exe及调用方式
Dec 21 #Python
python脚本后台执行方式
Dec 21 #Python
Python模块的制作方法实例分析
Dec 21 #Python
基于Python 中函数的 收集参数 机制
Dec 21 #Python
You might like
php5.3中连接sqlserver2000的两种方法(com与ODBC)
2012/12/29 PHP
WordPress中对访客评论功能的一些优化方法
2015/11/24 PHP
PHP常用工具类大全附全部代码下载
2015/12/07 PHP
Thinkphp3.2实用篇之计算型验证码示例
2017/02/09 PHP
PHP保存Base64图片base64_decode的问题整理
2019/11/04 PHP
php正则表达式使用方法整理集合
2020/01/31 PHP
jQuery使用手册之二 DOM操作
2007/03/24 Javascript
jquery 学习之二 属性(html()与html(val))
2010/11/25 Javascript
web性能优化之javascript性能调优
2012/12/28 Javascript
js获取IP地址的方法小结
2014/07/01 Javascript
Google官方支持的NodeJS访问API,提供后台登录授权
2014/07/29 NodeJs
node.js适合游戏后台开发吗?
2014/09/03 Javascript
jQuery多个input求和的实现方法
2015/02/12 Javascript
Javascript中Array用法实例分析
2015/06/13 Javascript
JS实现从顶部下拉显示的带动画QQ客服特效代码
2015/10/24 Javascript
javascript检测移动设备横竖屏
2016/05/21 Javascript
Jquery Easyui日历组件Calender使用详解(23)
2016/12/18 Javascript
原生js实现回复评论功能
2017/01/18 Javascript
Vue + Webpack + Vue-loader学习教程之功能介绍篇
2017/03/14 Javascript
JS异步文件上传(兼容IE8+)
2017/04/02 Javascript
jQuery实现常见的隐藏与展示列表效果示例
2018/06/04 jQuery
微信小程序下拉框功能的实例代码
2018/11/06 Javascript
js单线程的本质 Event Loop解析
2019/10/29 Javascript
Python OS模块常用函数说明
2015/05/23 Python
python实现批量注册网站用户的示例
2019/02/22 Python
WxPython建立批量录入框窗口
2019/02/27 Python
浅谈Python的条件判断语句if/else语句
2019/03/21 Python
Django框架model模型对象验证实现方法分析
2019/10/02 Python
如何使用Python调整图像大小
2020/09/26 Python
Python性能测试工具Locust安装及使用
2020/12/01 Python
Python爬虫之Selenium鼠标事件的实现
2020/12/04 Python
Opencv 图片的OCR识别的实战示例
2021/03/02 Python
英国在线定制百叶窗网站:Swift Direct Blinds
2020/02/25 全球购物
有限责任公司股东合作协议书范本
2014/10/30 职场文书
vue项目两种方式实现竖向表格的思路分析
2021/04/28 Vue.js
Nginx如何限制IP访问只允许特定域名访问
2022/07/23 Servers