python多线程爬虫实例-python多线程爬虫实例讲解
Python作为一门强大的脚本语言,我们经常使用python来写爬虫程序,简单的爬虫会写,可是用python写多线程网页爬虫,应该如何写呢?一般来说,使用线程有两种模式,一种是创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行.另一种是直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的class里。
实现python多线程(http://www.maiziedu.com/group/article/10324/)网页爬虫,采用了多线程和锁机制,实现了广度优先算法的网页爬虫。
先给大家简单介绍下我的实现思路:
对于一个网络爬虫,如果要按广度遍历的方式下载,它是这样的:
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,'... '
self.logfile.write("URL:"+g_queueURL[0]+"........")
self.downloadAll()
self.updateQueueURL()
content=' >>>Depth '+str(depth)+': '
self.logfile.write(content)
i=0
while i
content=str(g_totalcount+i)+'->'+g_queueURL+' '
self.logfile.write(content)
i+=1
def downloadAll(self):
global g_queueURL
global g_totalcount
i=0
while i
j=0
while j
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入口: ")
threadnum=int(raw_input("设置线程数:"))
crawlername="小小爬虫"
crawler=Crawler(crawlername,url,threadnum)
crawler.craw()
以上就用实例为大家讲解了python实现多线程爬虫的方法,有兴趣的朋友可以自己试试。
python多线程爬虫实例-python多线程爬虫实例讲解相关推荐
- python多线程爬虫实例-Python多线程在爬虫中的应用
题记:作为测试工程师经常需要解决测试数据来源的问题,解决思路无非是三种:(1)直接从生产环境拷贝真实数据 (2)从互联网上爬取数据 (3)自己用脚本或者工具造数据.前段时间,为了获取更多的测试数据,笔 ...
- python多线程爬虫实例-Python实现多线程爬虫
编辑推荐: 本文主要介绍对Python多线程爬虫实战的整体的思路,希望对大家有帮助. 本文来知乎,由火龙果软件Alice编辑,推荐. 最近在写爬虫程序爬取亚马逊上的评论信息,因此也自学了很多爬虫相关的 ...
- python多线程爬虫实例-Python3多线程爬虫实例讲解代码
多线程概述 多线程使得程序内部可以分出多个线程来做多件事情,充分利用CPU空闲时间,提升处理效率.python提供了两个模块来实现多线程thread 和threading ,thread 有一些缺点, ...
- python多线程爬虫实例-Python多线程爬虫简单示例
python是支持多线程的,主要是通过thread和threading这两个模块来实现的.thread模块是比较底层的模块,threading模块是对thread做了一些包装的,可以更加方便的使用. ...
- python回测工具_Python爬虫回测股票的实例讲解
股票和基金一直是热门的话题,很多周围的人都选择不同种类的理财方式.就股票而言,肯定是短时间内收益最大化,这里我们需要用python爬虫的方法,来帮助我们获取一些股票的数据,这样才能更好的买到相应的股票 ...
- python3线程gil_python3爬虫GIL修改多线程实例讲解
我们打开程序后,会发现电脑的内存和cpu发生了变化.在对于前者上面,自然是希望内容占用小,cpu的利用越高越好.那有没有什么方法可以让我们的cpu达到满状态的运行效果呢?这就得用到我们所学的多线程中的 ...
- UN Comtrade python爬虫实现,多线程动态ip
原帖见[爬虫]Python使用动态IP,多线程,爬取uncomtrade的数据_学金融的程序员懒羊羊的博客-CSDN博客_爬虫动态ip 修改了url代码,自定义函数的递归问题,跑通代码. 需要自己去i ...
- 网络爬虫Crawler~~~~python 爬虫~~~省市区~~抓~~快递公司~多线程
##网络爬虫 README_Crawler.md 网络爬虫技术 (java[Jsoup].python[Beautiful Soup]) 文件下载链接 下载链接2 2:查看 Python网络爬虫实战: ...
- python爬虫入门实例-Python爬虫快速入门:基本结构简单实例
本爬虫系列入门教程假设读者仅有一点点Python基础或者近乎为零的基础.如果是有Python基础的可以跳过一些对于Python基本知识的补充. 爬虫能干什么呢?一句话概括,正常通过浏览器可以获取的数据 ...
- python爬虫案例-Python爬取租房数据实例,据说可以入门爬虫的小案例!
一.什么叫爬虫 爬虫,又名"网络爬虫",就是能够自动访问互联网并将网站内容下载下来的程序.它也是搜索引擎的基础,像百度和GOOGLE都是凭借强大的网络爬虫,来检索海量的互联网信息的 ...
最新文章
- kubernetes离线一键安装教程
- 机器学习(MACHINE LEARNING)MATLAB求解利润最大化问题【线性规划】
- linux boost 卸载,Ubuntu下boost库的编译安装步骤及卸载方法详解
- scala命令行运行spark代码
- html中select标签刷新后不回到默认值而是保持之前选择值
- spring boot中servlet启动原理
- 微软宣布加入 OpenJDK 项目
- 传说中的WCF(4):发送和接收SOAP头
- ASP.NET基础教程-Server对象
- Doris SQL执行计划
- 把网站部署到IIS后访问不了,报错IIS管理器无法验证此内置账户是否有访问权
- 【湖南集训 4.2】正12面体
- 什么是软件研发费用定额?
- html 画excel表格边框,只需五分钟!用Excel做出美观的表格
- 时下常用有效的rss源
- Recovering Realistic Texture in Image Super-resolution by Deep Spatial Feature Transform
- 解决mysql sum求和返回null问题或IFNULL应用
- Concise,一款为hexo设计的简约而漂亮的主题
- python 制作抽奖_python制作抽奖程序代码详解
- 微阵列芯片服务器,功能性分群于微阵列芯片之应用