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 ...
随机推荐
- Zend Studio 下载
http://www.52pojie.cn/thread-507229-1-1.html THINKPHP : http://www.cnblogs.com/TigerYangWTH/p/57250 ...
- 11.Python使用Scrapy爬虫小Demo(新手入门)
1.前提:已安装好scrapy,且已新建好项目,编写小Demo去获取美剧天堂的电影标题名 2.在项目中创建一个python文件 3.代码如下所示: import scrapy class movies ...
- Oracle在线新增索引
Oracle新增索引语法很简单,如果是普通索引的话: create Index IDX_T_WLF on T_WLF(ACTIVITYID,ACTIVETIME) tablespace TBS_VCO ...
- U盘永久系统-centos
U盘永久系统-centos 问题: 服务器centos系统崩溃,重装需要备份其中数据,约4T,实验室有远程存储服务器,然而rescue模式进去后无法挂载远程存储,只好做一个真正的U盘系统解决了. 方案 ...
- windows10 vs2015编译 带nginx-rtmp-module 模块的32位nginx
1 下载必要软件 从 http://xhmikosr.1f0.de/tools/msys/下载msys:http://xhmikosr.1f0.de/tools/msys/MSYS_MinGW-w6 ...
- python 网络编程--socket模块/struct模块
socket模块: 客户端:CS架构, client -> server 浏览器:BS架构, browser -> server 网络通信本质:传输字节 doc命令查看ip地址:ipc ...
- 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
- 阻塞队列之四:ArrayBlockingQueue
一.ArrayBlockingQueue简介 一个由循环数组支持的有界阻塞队列.它的本质是一个基于数组的BlockingQueue的实现. 它的容纳大小是固定的.此队列按 FIFO(先进先出)原则对元 ...
- python学习 (二十八) Python的for 循环
1: for 循环可以循环如下类型: my_string = "abcabc" // 字符串类型 for c in my_string: print(c, end=' ') car ...
- StringsUtil字符串工具类---灵活截取
package com.js.ai.modules.pointwall.interfac; import javax.print.attribute.standard.MediaName; publi ...