#!/usr/bin/env python
#coding=utf-8
import threading
import urllib
import re
import time cur=0
last=0
totalcount=0
depth=0
t_mutex=threading.Condition() class Mycrawler:
def __init__(self,crawlername,seeds,threadnum):
self.crawlername=crawlername
self.seeds=seeds
self.crawqueue=CrawQueue()
self.initQueue(self.seeds)
self.threadnum=threadnum
self.threadpools=[]
self.logfile=file('log2.txt','w')
def initQueue(self,seeds):
if isinstance(seeds,str):
self.crawqueue.push(seeds)
elif isinstance(seeds,list):
for seed in seeds:
self.crawqueue.push(seed)
global last
global totalcount
totalcount=self.crawqueue.getQueueCount()
last=totalcount
def crawling(self):
global cur
global depth
global last
global totalcount
self.log(">>>Depth "+str(depth)+":\n")
while self.crawqueue.getQueueCount()!=0:
url=self.crawqueue.pop()
self.log(url)
if url==None:
continue
self.crawqueue.addToVisited(url)
links=self.getLinks(url)
if links==None:
print 'None'
self.crawqueue.failed.append(url)
continue
beforenum = self.crawqueue.getQueueCount()
self.crawqueue.addLinks(links)
afternum = self.crawqueue.getQueueCount()
totalcount+=afternum-beforenum
cur+=1
if cur==last:
depth+=1
self.log(">>>Depth "+str(depth)+":\n")
last=totalcount
def crawling2(self):
global last
global totalcount
global depth
self.log(">>>Depth "+str(depth)+":\n")
totalcount=self.crawqueue.getQueueCount()
last=totalcount
while self.crawqueue.getQueueCount()!=0:
for i in range(self.threadnum):
url=self.crawqueue.pop()
if url==None:
break
crawthread=crawlerThread(url,i,self)
self.threadpools.append(crawthread)
crawthread.start()
for i in range(len(self.threadpools)):
crawthread=self.threadpools[i]
crawthread.join(30)
def log(self,content):
self.logfile.write(content+"\n")
class crawlerThread(threading.Thread):
def __init__(self,url,tid,mycrawler):
threading.Thread.__init__(self)
self.url=url
self.tid=tid
self.mycrawler=mycrawler
def run(self):
global t_mutex
global cur
global last
global totalcount
global depth
t_mutex.acquire()
self.mycrawler.log(self.url)
t_mutex.release()
links=self.getLinks(self.url)
if links==None:
t_mutex.acquire()
self.mycrawler.crawqueue.addToVisited(self.url)
self.mycrawler.crawqueue.addToFailed(self.url)
t_mutex.release()
else:
t_mutex.acquire()
self.mycrawler.crawqueue.addToVisited(self.url)
beforenum=self.mycrawler.crawqueue.getQueueCount()
self.mycrawler.crawqueue.addLinks(links)
afternum =self.mycrawler.crawqueue.getQueueCount()
totalcount+=afternum-beforenum
t_mutex.release()
t_mutex.acquire()
cur+=1
if cur==last:
depth+=1
self.mycrawler.log(">>>Depth "+str(depth)+":\n")
last=totalcount
t_mutex.release()
def getLinks(self,url):
try:
page=urllib.urlopen(url)
html=page.read()
reg=r'"(http://.+?)"'
regob=re.compile(reg,re.DOTALL)
links=regob.findall(html)
return links
except:
print 'Failed downloading and saving',url
return None
class CrawQueue:
def __init__(self):
self.queue=[]
self.visited=[]
self.failed=[]
def getQueue(self):
return self.queue
def getVisited(self):
return self.visited
def getFailed(self):
return self.failed
def push(self,url):
if url!="" and url not in self.queue and url not in self.visited:
self.queue.insert(0,url)
def pop(self):
if len(self.queue)==0:
#print 'failed to pop: queue is empty'
return None
else:
return self.queue.pop()
def isEmpty(self):
if len(self.queue)==0:
return 1
else:
return 0
def addToVisited(self,url):
self.visited.append(url)
def addToFailed(self,url):
self.failed.append(url)
def remove(self,url):
self.queue.remove(url)
def getVisitedCount(self):
return len(self.visited)
def getQueueCount(self):
return len(self.queue)
def addLinks(self,links):
for link in links:
self.push(link) if __name__=="__main__":
seeds="http://www.douban.com/"
threadnum=int(raw_input("设置线程数:"))
crawlername="小小爬虫"
mycrawler=Mycrawler(crawlername,seeds,threadnum)
mycrawler.crawling2()

多线程网页爬虫 python 实现(二)的更多相关文章

  1. 多线程网页爬虫 python 实现

    采用了多线程和锁机制,实现了广度优先算法的网页爬虫. 对于一个网络爬虫,如果要按广度遍历的方式下载,它就是这样干活的:         1.从给定的入口网址把第一个网页下载下来         2.从 ...

  2. python网页爬虫开发之二

    1.网站robots robotparser模块首先加载robots.txt文件,然后通过can_fetch()函数确定指定的用户代理是否允许访问网页. 2.识别网站技术 3.下载网页 使用urlli ...

  3. python 网页爬虫+保存图片+多线程+网络代理

    今天,又算是浪费了一天了.python爬虫,之前写过简单的版本,那个时候还不懂原理,现在算是收尾吧. 以前对网页爬虫不了解,感觉非常神奇,但是解开这面面纱,似乎里面的原理并不是很难掌握.首先,明白一个 ...

  4. Python爬虫初学(二)—— 爬百度贴吧

    Python爬虫初学(二)-- 爬百度贴吧 昨天初步接触了爬虫,实现了爬取网络段子并逐条阅读等功能,详见Python爬虫初学(一). 今天准备对百度贴吧下手了,嘿嘿.依然是跟着这个博客学习的,这次仿照 ...

  5. Python 网页爬虫 & 文本处理 & 科学计算 & 机器学习 & 数据挖掘兵器谱(转)

    原文:http://www.52nlp.cn/python-网页爬虫-文本处理-科学计算-机器学习-数据挖掘 曾经因为NLTK的缘故开始学习Python,之后渐渐成为我工作中的第一辅助脚本语言,虽然开 ...

  6. Python网页爬虫(一)

    很多时候我们想要获得网站的数据,但是网站并没有提供相应的API调用,这时候应该怎么办呢?还有的时候我们需要模拟人的一些行为,例如点击网页上的按钮等,又有什么好的解决方法吗?这些正是python和网页爬 ...

  7. Python爬虫学习:二、爬虫的初步尝试

    我使用的编辑器是IDLE,版本为Python2.7.11,Windows平台. 本文是博主原创随笔,转载时请注明出处Maple2cat|Python爬虫学习:二.爬虫的初步尝试 1.尝试抓取指定网页 ...

  8. 【Python】Python 网页爬虫 & 文本处理 & 科学计算 & 机器学习 & 数据挖掘兵器谱

    本文转载自:https://www.cnblogs.com/colipso/p/4284510.html 好文 mark http://www.52nlp.cn/python-%E7%BD%91%E9 ...

  9. Python 3实现网页爬虫

    1 什么是网页爬虫 网络爬虫( 网页蜘蛛,网络机器人,网页追逐者,自动索引,模拟程序)是一种按照一定的规则自动地抓取互联网信息的程序或者脚本,从互联网上抓取对于我们有价值的信息.Tips:自动提取网页 ...

随机推荐

  1. Hi3519V101 SDK安装以及开发环境搭建

    Hi3519V101 Linux开发环境 1.安装Hi3519V101 SDKHi3519V101 SDK是基于Hi3519V101 DMEB的软件开发包,包含了在Linux相关应用开发时使用的各种工 ...

  2. 数据库---大数据+hadoop

    大数据:hadoop:大数据和hadoop的关系

  3. ntdsutil 清理弃用服务器-----待验证

    例子是这样的: 一个森林里有两个树,mm.com和cc.com,分别有dc www.mm.com和vdc.cc.com, cc.com域的控制器崩溃,不想恢复,要彻底删除这个域,由于vdc.cc.co ...

  4. 剑指offer面试题43:n个筛子的点数

    题目描述: 把n个筛子扔在地上,所有筛子朝上的一面点数之和为s,输入n,打印出s的所有可能的值出线的概率. 书上给了两种解法,第一种递归的方法由于代码太乱,没有看懂=.= 第二种方法很巧妙,lz已经根 ...

  5. 【LeetCode】String Without AAA or BBB(不含 AAA 或 BBB 的字符串)

    这道题是LeetCode里的第984道题. 题目要求: 给定两个整数 A 和 B,返回任意字符串 S,要求满足: S 的长度为 A + B,且正好包含 A 个 'a' 字母与 B 个 'b' 字母: ...

  6. Linux下dpkg的用法

    转自:http://blog.csdn.net/fireblue1990/article/details/52627952 dpkg是一个Debian的一个命令行工具,它可以用来安装.删除.构建和管理 ...

  7. [android开发篇]权限分类:正常权限和危险权限

    https://developer.android.com/guide/topics/security/permissions.html#normal-dangerous 系统权限 本文内容 安全架构 ...

  8. javascript异常cannot read property xx of null 的错误

    一般报这种异常或者错误,是因为试图从null中再读一个属性导致的. 比如:var myAttr=myObj.data.Name; 假如这个时候myObj.data是null,那么再试图读取data的N ...

  9. Codeforces Round #352 (Div. 1) B. Robin Hood

    B. Robin Hood 讲道理:这种题我是绝对不去(敢)碰的.比赛时被这个题坑了一把,对于我这种不A不罢休的人来说就算看题解也要得到一个Accepted. 这题网上有很多题解,我自己是很难做出来的 ...

  10. POJ-2186 Popular Cows,tarjan缩点找出度为0的点。

    Popular Cows 题意:一只牛崇拜另外一只牛,这种崇拜关系可以传导.A->B,B->C =>A->C.现在给出所有的关系问你有多少牛被其他所有的牛都崇拜. 思路:就是一 ...