多线程糗事百科案例

案例要求参考上一个糗事百科单进程案例:http://www.cnblogs.com/miqi1992/p/8081929.html

Queue(队列对象)

Queue是python中的标准库,可以直接import Queue引用;队列时线程间最常用的交互数据的形式。

python下多线程的思考

对于资源,加锁是个重要的环节。因为python原生的list,dict等,都是not thread safe的。而Queue,是线程安全的,因此在满足使用条件下,建议使用队列

  1. 初始化:class Queue.Queue(maxsize)FIFO先进先出

  2. 包中的常用方法:

    • Queue.qszie()返回队列的大小
    • Queue.empty()如果队列为空,返回True,否则返回False
    • Queue.full()如果队列满了,返回True,反之False
    • Queue.full 与 maxsize大小对应
    • Queue.get([block[, timeout]])获取队列,timeout等待事件
  3. 创建一个"队列"对象

    • import Queue
    • myqueue = Queue.Queue(maxsize=10)
  4. 将一个值放入队列中

    • myqueue.put(10)
  5. 将一个值从队列中取出

    • myqueue.get()

多线程示意图

#-*- coding:utf-8 -*-

import requests
from lxml import etree
from Queue import Queue
import threading
import time
import json class Thread_crawl(threading.Thread):
"""
抓取线程类
"""
def __init__(self, threadID, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.q = q def run(self):
print("String: "+self.threadID)
self.qiushi_spider()
print("Exiting: "+self.threadID) def qiushi_spider(self):
while True:
if self.q.empty():
break
else:
page = self.q.get()
print('qiushi_spider=', self.threadID, 'page=', str(page))
url = 'http://www.qiushibaike.com/8hr/page/' + str(page)+"/"
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
'Accept-Language':'zh-CN,zh;q=0.8'
} #多次尝试失败结束,防止死循环
timeout = 4
while timeout > 0:
timeout -= 1
try:
content = requests.get(url, headers = headers)
data_queue.put(content.text)
break
except Exception, e:
print "qiushi_spider", e
if timeout < 0:
print 'timeout', url class Thread_Parser(threading.Thread):
"""
页面解析类
"""
def __init__(self, threadID, queue, lock, f):
threading.Thread.__init__(self)
self.threadID = threadID
self.queue = queue
self.lock = lock
self.f = f def run(self):
print("starting ", self.threadID)
global total, exitFlag_Parser
while not exitFlag_Parser:
try:
"""
调用队列对象的get()方法从队头删除并返回一个项目。可选参数为block, 默认为True
如果队列为空且block为True,get()就使调用线程暂停,直至有项目可用
如果队列为空且block为False,队列将引发Empty异常
"""
item = self.queue.get(False)
if not item:
pass
self.parse_data(item)
self.queue.task_done()
print("Thread_Parser=", self.threadID, 'total=', total)
except:
pass
print "Exiting ", self.threadID def parse_data(self, item):
"""
解析网页函数
:param item:网页内容
:return
"""
global total
try:
html = etree.HTML(item)
result = html.xpath('//div[contains(@id,"qiushi_tag")]')
for site in result:
try:
imgUrl = site.xpath('.//img/@src')[0]
title = site.xpath('.//h2')[0].text
content = site.xpath('.//div[@class="content"]/span')[0].text.strip()
vote = None
comments = None
try:
# 投票次数
vote = site.xpath('.//i')[0].text
# print(vote)
#print site.xpath('.//*[@class="number"]')[0].text
# 评论信息
comments = site.xpath('.//i')[1].text
except:
pass
result = {
'imageUrl' : imgUrl,
'title' : title,
'content' : content,
'vote' : vote,
'comments' : comments } with self.lock:
self.f.write(json.dumps(result, ensure_ascii=False).encode('utf-8') + '\n')
except Exception, e:
print("site in result ", e)
except Exception, e:
print("parse_data", e)
with self.lock:
total += 1 data_queue = Queue()
exitFlag_Parser = False
lock = threading.Lock()
total = 0 def main():
output = open('qiushibaike.json', 'a')
#初始化网页页码page从1-10个页面
pageQueue = Queue(10)
for page in range(1, 11):
pageQueue.put(page) #初始化采集线程
crawlthreads = []
crawllist = ["crawl-1", "crawl-2", "crawl-3"] for threadID in crawllist:
thread = Thread_crawl(threadID, pageQueue)
thread.start()
crawlthreads.append(thread) # #初始化解析线程parseList
parserthreads = []
parserList = ["parser-1", "parser-2", "parser-3"] #分别启动parserList
for threadID in parserList:
thread = Thread_Parser(threadID, data_queue, lock, output)
thread.start()
parserthreads.append(thread) # 等待队列情况
while not pageQueue.empty():
pass #等待所有线程完成
for t in crawlthreads:
t.join()
while not data_queue.empty():
pass #通知线程退出
global exitFlag_Parser
exitFlag_Parser = True for t in parserthreads:
t.join()
print 'Exiting Main Thread'
with lock:
output.close() if __name__ == '__main__':
main()

Python爬虫(十八)_多线程糗事百科案例的更多相关文章

  1. [Python]网络爬虫(八):糗事百科的网络爬虫(v0.2)源码及解析

    转自:http://blog.csdn.net/pleasecallmewhy/article/details/8932310 项目内容: 用Python写的糗事百科的网络爬虫. 使用方法: 新建一个 ...

  2. python 多线程糗事百科案例

    案例要求参考上一个糗事百科单进程案例 Queue(队列对象) Queue是python中的标准库,可以直接import Queue引用;队列是线程间最常用的交换数据的形式 python下多线程的思考 ...

  3. 芝麻HTTP:Python爬虫实战之爬取糗事百科段子

    首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 友情提示 糗事百科在前一段时间进行了改版,导致之前的代码没法用了,会导致无法输出和CPU占用过高的 ...

  4. python 爬虫实战1 爬取糗事百科段子

    首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 本篇目标 抓取糗事百科热门段子 过滤带有图片的段子 实现每按一次回车显示一个段子的发布时间,发布人 ...

  5. Python爬虫实战之爬取糗事百科段子

    首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 友情提示 糗事百科在前一段时间进行了改版,导致之前的代码没法用了,会导致无法输出和CPU占用过高的 ...

  6. Python爬虫实战之爬取糗事百科段子【华为云技术分享】

    首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 友情提示 糗事百科在前一段时间进行了改版,导致之前的代码没法用了,会导致无法输出和CPU占用过高的 ...

  7. [python]爬虫学习(三)糗事百科

    import requestsimport osfrom bs4 import BeautifulSoupimport timepage=2url='http://www.qiushibaike.co ...

  8. python爬虫——利用BeautifulSoup4爬取糗事百科的段子

    import requests from bs4 import BeautifulSoup as bs #获取单个页面的源代码网页 def gethtml(pagenum): url = 'http: ...

  9. Python爬虫(十七)_糗事百科案例

    糗事百科实例 爬取糗事百科段子,假设页面的URL是: http://www.qiushibaike.com/8hr/page/1 要求: 使用requests获取页面信息,用XPath/re做数据提取 ...

随机推荐

  1. 定制rpm包---Yum环境搭建

    1.1 在yum服务器上创建yum仓库命令 mkdir -p /application/nginx/html/yum cd /application/nginx/html/yum rz #上传rpm包 ...

  2. npminstall无法安装node-sass

    cannot download "https://hithub.com/sass/node-sass/releases/download/v3.13.0/win32-x64-46_bindi ...

  3. Docker安装Mysql数据库容器(zz)

    zz自:http://blog.csdn.net/chengxuyuanyonghu/article/details/54380032 1.下载mysql的镜像: sudo docker pull m ...

  4. Lucene全文检索引擎

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...

  5. 【分享】纯jQuery实现星巴克官网导航栏效果

    前言 大冬天的没得玩,只能和代码玩. 所以就无聊研究了一下星巴克官网,在我看来应该是基本还原吧~ 请各位大神指教! 官网效果图 要写的就是最上方的会闪现的白色条条 效果分析 1.在滚动条往下拉到一定距 ...

  6. Python的__init__.py用法

    python中包的引入,对于大型项目中都会使用到这个功能,把实现不同功能的python文件放在一起,组成不同lib库,然后在其他地方调用. 包,python源文件+__init__.py 模块,pyt ...

  7. percona_xtrabackup

    原理 percona xtrabackup备份过程主要分为以下几点: 1.xtrabackup在启动时会记住LSN(log sequence number),然后复制所有的数据文件 2.xtrabac ...

  8. 两种数据传输的方式——get和post。

    Form提供了两种数据传输的方式——get和post.虽然它们都是数据的提交方式,但是在实际传输时确有很大的不同,并且可能会对数据产生严重的影响.虽然为了方便的得到变量值,Web容器已经屏蔽了二者的一 ...

  9. ssh、scp免秘钥远程执行命令:expect

    首先安装expect # yum -y install expect 命令格式 # ./expect IP COMM    #expect是独立的工具,所以不能用sh来执行 1 2 3 4 5 6 7 ...

  10. 常用接口简析2---IComparable和IComparer接口的简析

    常用接口的解析(链接) 1.IEnumerable深入解析 2.IEnumerable.IEnumerator接口解析 3.IList.IList接口解析 默认情况下,对象的Equals(object ...