php多线程抓取网页(使用线程有两种模式一种代码如下分享方法分享 )
优采云 发布时间: 2022-03-13 11:03php多线程抓取网页(使用线程有两种模式一种代码如下分享方法分享
)
一般来说,使用线程有两种模式。一种是创建一个线程要执行的函数,把这个函数传给Thread对象,让它执行。另一种是直接继承Thread,新建一个类。将线程执行的代码放入这个新类中。
实现多线程网络爬虫,利用多线程加锁机制实现广度优先算法的网络爬虫。
首先简单介绍一下我的实现思路:
对于一个网络爬虫来说,如果你想通过广度遍历下载,是这样的:
1.从给定的门户 URL 下载第一个网页
2.从第一个网页中提取所有新的网址并放入下载列表
3.点击下载列表中的地址下载所有新页面
4.从所有新网页中找出尚未下载的网页地址并更新下载列表
5.重复3、4两步,直到更新的下载列表为空并停止
python代码如下:
<p>
#!/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