https://www.cnblogs.com/alamZ/p/7414020.html   课件内容

#_*_ coding: utf-8 _*_
'''
Created on 2018年7月17日
@author: sss
function: 利用多线程爬取糗事百科页面 '''
#使用线程库
import threading
#队列
from queue import Queue
#解析库
from lxml import etree
#json处理
import json
import time
import requests
from pickle import FALSE CRAWL_EXIT = False
PARSE_EXIT = False class TreadCrawl(threading.Thread):
def __init__(self, threadName, pageQueue, dataQueue):
#threading.Thread.__init__(self)
#掉用父类初始化方法
super(TreadCrawl, self).__init__()
#线程名
self.threadName = threadName
#页码队列
self.pageQueue = pageQueue
#数据队列
self.dataQueue = dataQueue
#请求报头
self.headers = {"User-Agent" : "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;"} def run(self):
print('启动' + self.threadName)
while not CRAWL_EXIT:
try:
#取出一个数字,先进先出
#课选参数block,默认值为True
#1.如果对列为空,block为True的话,不会结束,会进入阻塞转态,直到队列有新的数据
#2.如果队列为空,block为false的话,就弹出一个Queue.empty()异常
page = self.pageQueue.get(False)
url = "http://www.qiushibaike.com/8hr/page/" + str(page) +"/"
content = requests.get(url, headers = self.headers).text
time.sleep(1)
self.dataQueue.put(content)
except:
pass
print('结束' + self.threadName) class ThreadParse(threading.Thread):
def __init__(self, threadName, dataQueue, filename, lock):
# print('parse')
super(ThreadParse, self).__init__()
#线程名
self.threadName = threadName
#数据队列
self.dataQueue = dataQueue
#保存解析后数据的文件名
self.filename = filename
#锁
self.lock = lock def run(self):
print('启动' + self.threadName)
while not PARSE_EXIT:
try:
html = self.dataQueue.get(False)
# print('0000000000000000000')
self.parse(html)
except:
pass
print('退出' + self.threadName) def parse(self, html):
#解析为HTML DOM
html = etree.HTML(html) node_list = html.xpath('//div[contains(@id, "qiushi_tag_")]')
# print(node_list)
# print('6666666666666')
items = {}
for node in node_list:
#用户名
# username = node.xpath('./div/a/h2')[0].text
username = node.xpath('.//h2')[0].text.replace('\n','') #用replace去掉\n
#图片连接
image = node.xpath('.//img/@src')#[0]
#取出标题下的内容
content = node.xpath('./a/div/span')[0].text.replace('\n','')
#点赞
zan = node.xpath('./div/span/i')[0].text
#评论
comment = node.xpath('./div/span/a/i')[0].text items = {
'username' : username,
'image' : image,
'content' : content,
'zan' : zan,
'comments' : comment
} # with 后面有两个必须执行的操作:__enter__ 和 __exit__
# 不管里面的操作结果如何,都会执行打开、关闭
# 打开锁、处理内容、释放锁
with self.lock:
# 写入存储的解析后的数据
self.filename.write(json.dumps(items, ensure_ascii = False) + "\n")
print('已写入') def main():
#页码队列,表示20个页面
pageQueue = Queue(20)
#放入1~20的数字,先进先出
for i in range(1, 5):
pageQueue.put(i) #采集的结果(每页的html原码)的数据队列,参数为空表示不限制
dataQueue = Queue() #打开文件
filename = open('./qiushi/duanzi.json', 'a', encoding='utf-8') #创建锁:
lock = threading.Lock() #三个采集的名字
crawlList = ['采集线程 1号','采集线程 2号','采集线程 3号'] #存储三个采集线程的列表集合
threadcrawl = []
for threadName in crawlList:
thread = TreadCrawl(threadName, pageQueue, dataQueue)
thread.start()
threadcrawl.append(thread) #三个解析线程的名字
parseList = ['解析线程1号', '解析线程2号', '解析线程3号']
#存储三个解析线程
threadparse = []
for threadName in parseList:
thread = ThreadParse(threadName, dataQueue, filename, lock)
thread.start()
threadparse.append(thread) #等待pageQueue队列为空,也就是等待之前的操作执行完毕,
while not pageQueue.empty():
pass #如果pageQueue为空,采集线程退出循环
global CRAWL_EXIT
CRAWL_EXIT = True print('pageQueue为空') for thread in threadcrawl:
thread.join()
print(1) while not dataQueue.empty():
pass global PARSE_EXIT
PARSE_EXIT = True for thread in threadparse:
thread.join()
print('2') with lock:
#关闭文件
filename.close()
print('谢谢使用!') if __name__ == "__main__":
main()

  

16-多线程爬取糗事百科(python+Tread)的更多相关文章

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

    大家好,前面入门已经说了那么多基础知识了,下面我们做几个实战项目来挑战一下吧.那么这次为大家带来,Python爬取糗事百科的小段子的例子. 首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把 ...

  2. 8.Python爬虫实战一之爬取糗事百科段子

    大家好,前面入门已经说了那么多基础知识了,下面我们做几个实战项目来挑战一下吧.那么这次为大家带来,Python爬取糗事百科的小段子的例子. 首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把 ...

  3. python网络爬虫--简单爬取糗事百科

    刚开始学习python爬虫,写了一个简单python程序爬取糗事百科. 具体步骤是这样的:首先查看糗事百科的url:http://www.qiushibaike.com/8hr/page/2/?s=4 ...

  4. python爬虫之爬取糗事百科并将爬取内容保存至Excel中

    本篇博文为使用python爬虫爬取糗事百科content并将爬取内容存入excel中保存·. 实验环境:Windows10   代码编辑工具:pycharm 使用selenium(自动化测试工具)+p ...

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

    静觅 » Python爬虫实战一之爬取糗事百科段子 首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 友情提示 糗事百科在前一段时间进行了改版,导致 ...

  6. [爬虫]用python的requests模块爬取糗事百科段子

    虽然Python的标准库中 urllib2 模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests 自称 “HTTP for Humans”,说明使用更 ...

  7. 初识python 之 爬虫:使用正则表达式爬取“糗事百科 - 文字版”网页数据

    初识python 之 爬虫:使用正则表达式爬取"古诗文"网页数据 的兄弟篇. 详细代码如下: #!/user/bin env python # author:Simple-Sir ...

  8. python学习(十六)写爬虫爬取糗事百科段子

    原文链接:爬取糗事百科段子 利用前面学到的文件.正则表达式.urllib的知识,综合运用,爬取糗事百科的段子先用urllib库获取糗事百科热帖第一页的数据.并打开文件进行保存,正好可以熟悉一下之前学过 ...

  9. python爬取糗事百科段子

    初步爬取糗事百科第一页段子(发布人,发布内容,好笑数和评论数) #-*-coding:utf--*- import urllib import urllib2 import re page = url ...

随机推荐

  1. win10下安装并启动zookeeper

    下载直接到zk的官网(zookeeper.apache.org)即可,点击右边的Releases,在Download下再点Download进入镜像下载页面,在给出的链接列表里选择一个镜像地址,进去后选 ...

  2. python3api-ms-win-crt-runtime-l1-1-0.dll丢失解决方法

    先记录一个之前遇到的问题: 在安装了pycharm后,发现 通过上网发现,其实就是没有安装pip和setuptools,其实 Python3以后都是默认安装pip的,所以最后的解决办法是将我目前的Py ...

  3. Unit08: Spring集成mybatis

    Unit08: Spring集成mybatis 1. Spring集成mybatis (1)方式一 step1. 导包. spring-webmvc,mybatis,mybatis-spring, o ...

  4. 基于INTEL FPGA硬浮点DSP实现卷积运算

    概述 卷积是一种线性运算,其本质是滑动平均思想,广泛应用于图像滤波.而随着人工智能及深度学习的发展,卷积也在神经网络中发挥重要的作用,如卷积神经网络.本参考设计主要介绍如何基于INTEL 硬浮点的DS ...

  5. GOF23设计模式之备忘录模式(memento)

    一.备忘录模式概述 保存某个对象内部状态的拷贝,使得以后就可以将该对象恢复到原先的状态. 结构: (1)源发器类 Originator   负责创建一个备忘录 Memento,用以记录当前时刻它的内部 ...

  6. com.mysql.jdbc.PacketTooBigException: Packet for query is too large (4593 > 1024)

    修改 my.conf ,增加max_allowed_packet=8M window中, 进入mysql的 bin目录 执行  :修改 my.conf ,增加max_allowed_packet=8M

  7. node的模块管理

    /* *一:从node_modules目录中加载模块; * 向这样的写法: * require("aa.js") * 则node将aa.js文件视为node_modules目录下的 ...

  8. oracle 索引使用小结

    1. 普通索引 create index my_index on test (col_1); 可创建合并两列或多列的索引,最多可将32列合并在一个索引中(位图索引最多可合并30列) create in ...

  9. Oracle block 格式

    Oracle block 格式 信息参考:  http://www.ixora.com.au/ 特别感谢 overtime 大哥对我的无私的帮助和对我一直鼓励支持我的网友这些资料是没得到oracle ...

  10. nova volume-create的使用

    处理cinder可以直接创建volume外,nova也是可以的 如: 可以看出创建一个名字为volume2的卷,大小为10G 把创建好的volume2卷直接挂在vm虚拟机上 如:先查看计算节点有几个v ...