基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实现多线程网页爬虫,希望大家喜欢。

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。 Python以简洁和强大的生态系统着称,C 则以高性能和底层控制能力闻名。

2小时内可以学会Python的基本编程概念和技能。1.学习变量和数据类型,2.掌握控制流(条件语句和循环),3.理解函数的定义和使用,4.通过简单示例和代码片段快速上手Python编程。

Python在游戏和GUI开发中表现出色。1)游戏开发使用Pygame,提供绘图、音频等功能,适合创建2D游戏。2)GUI开发可选择Tkinter或PyQt,Tkinter简单易用,PyQt功能丰富,适合专业开发。

两小时内可以学到Python的基础知识。1.学习变量和数据类型,2.掌握控制结构如if语句和循环,3.了解函数的定义和使用。这些将帮助你开始编写简单的Python程序。

Python更易学且易用,C 则更强大但复杂。1.Python语法简洁,适合初学者,动态类型和自动内存管理使其易用,但可能导致运行时错误。2.C 提供低级控制和高级特性,适合高性能应用,但学习门槛高,需手动管理内存和类型安全。

要在有限的时间内最大化学习Python的效率,可以使用Python的datetime、time和schedule模块。1.datetime模块用于记录和规划学习时间。2.time模块帮助设置学习和休息时间。3.schedule模块自动化安排每周学习任务。

Python在web开发、数据科学、机器学习、自动化和脚本编写等领域有广泛应用。1)在web开发中,Django和Flask框架简化了开发过程。2)数据科学和机器学习领域,NumPy、Pandas、Scikit-learn和TensorFlow库提供了强大支持。3)自动化和脚本编写方面,Python适用于自动化测试和系统管理等任务。

Python在自动化、脚本编写和任务管理中表现出色。1)自动化:通过标准库如os、shutil实现文件备份。2)脚本编写:使用psutil库监控系统资源。3)任务管理:利用schedule库调度任务。Python的易用性和丰富库支持使其在这些领域中成为首选工具。
