16-多线程爬取糗事百科(python+Tread)
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)的更多相关文章
- Python爬虫实战一之爬取糗事百科段子
大家好,前面入门已经说了那么多基础知识了,下面我们做几个实战项目来挑战一下吧.那么这次为大家带来,Python爬取糗事百科的小段子的例子. 首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把 ...
- 8.Python爬虫实战一之爬取糗事百科段子
大家好,前面入门已经说了那么多基础知识了,下面我们做几个实战项目来挑战一下吧.那么这次为大家带来,Python爬取糗事百科的小段子的例子. 首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把 ...
- python网络爬虫--简单爬取糗事百科
刚开始学习python爬虫,写了一个简单python程序爬取糗事百科. 具体步骤是这样的:首先查看糗事百科的url:http://www.qiushibaike.com/8hr/page/2/?s=4 ...
- python爬虫之爬取糗事百科并将爬取内容保存至Excel中
本篇博文为使用python爬虫爬取糗事百科content并将爬取内容存入excel中保存·. 实验环境:Windows10 代码编辑工具:pycharm 使用selenium(自动化测试工具)+p ...
- 转 Python爬虫实战一之爬取糗事百科段子
静觅 » Python爬虫实战一之爬取糗事百科段子 首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 友情提示 糗事百科在前一段时间进行了改版,导致 ...
- [爬虫]用python的requests模块爬取糗事百科段子
虽然Python的标准库中 urllib2 模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests 自称 “HTTP for Humans”,说明使用更 ...
- 初识python 之 爬虫:使用正则表达式爬取“糗事百科 - 文字版”网页数据
初识python 之 爬虫:使用正则表达式爬取"古诗文"网页数据 的兄弟篇. 详细代码如下: #!/user/bin env python # author:Simple-Sir ...
- python学习(十六)写爬虫爬取糗事百科段子
原文链接:爬取糗事百科段子 利用前面学到的文件.正则表达式.urllib的知识,综合运用,爬取糗事百科的段子先用urllib库获取糗事百科热帖第一页的数据.并打开文件进行保存,正好可以熟悉一下之前学过 ...
- python爬取糗事百科段子
初步爬取糗事百科第一页段子(发布人,发布内容,好笑数和评论数) #-*-coding:utf--*- import urllib import urllib2 import re page = url ...
随机推荐
- angular-ui-bootstrap弹出框的使用(一)
在开发项目时,我们经常性的会遇到弹出框的需求,例如登陆,注册,添加信息等等....面对这一需求,我们当然也可以使用自己的双手进行编写,如果你时间充足可以试试. 今天我们讲解一下如何在angular框架 ...
- 一篇文章学LINQ(原创)
本篇文章主要介绍linq的基本用法,采用sql和linq比较的方式由浅入深进行学习, 注意:此文章是根据真实表来进行案例说明,表结构如下: 表1: Student(学生表) ...
- 制作mysql数据快照
在建立主从关系时,如果主上有旧数据,需要将旧数据拷贝到每一个从上.下面介绍几种不同的拷贝方式. 方法一:使用mysqldump工具创建一个你想要复制的所有数据库的一个dump.这是推荐使用的方法,特别 ...
- Hive使用druid做连接池代码实现
配置文档 hive_jdbc_url=jdbc:hive2://192.168.0.22:10000/default hive.dbname=xxxxx hive_jdbc_username=root ...
- 侯捷stl学习笔记链接
http://www.cnblogs.com/ranjiewen/category/799058.html http://www.cnblogs.com/ranjiewen/p/8260275.htm ...
- 为什么多线程读写 shared_ptr 要加锁?
https://www.cnblogs.com/Solstice/archive/2013/01/28/2879366.html 为什么多线程读写 shared_ptr 要加锁? 陈硕(giantch ...
- Clustering Factor——索引的成本指标
使用索引是我们面对海量数据搜索是一种常用的手段.通过有效的索引访问,可以使我们更快的访问到需要的数据,减少物理.逻辑IO,从而提高系统性能.在CBO时代,Oracle对于提交SQL的执行路径是有所选择 ...
- Idea2016远程调试Java项目
一.在IDEA中配置远程tomcat 1.打开配置页面 选择"+" → "Tomcat Server" → "Remote" 填写名称和目标 ...
- Rplot
#!/usr/bin/Rscriptlibrary(ggplot2) cf = read.table(file = 'result_sort.txt', header = TRUE, sep='\t' ...
- 1.docker学习之简介
什么是Docker Docker是一个开源的应用容器引擎.通俗来说:所谓开源,就是指Docker是开放源代码的,比如用户可以免费使用该源代码, 并在该源代码的基础上自由修改或传播.所谓引擎,指的是程序 ...