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. 一行代码搞定 FTP 服务

    环境搭建: python windows/linux pip install pyftpdlib (安装失败请到这里下载:https://pypi.python.org/pypi/pyftpdlib/ ...

  2. UI“三重天”之实践Uiautomator1

    说起来Uiautomator也有一年没碰过了.借此来回顾.总结一下. 也是阅读<精通APP自动化测试>一书.实践出真知的一个框架.编写了部分移动端UI自动化脚本.后续再深入学习. 虽然现在 ...

  3. css移除a标签及map、area(图片热区映射)点击过后的边框

    默认a标签及其包含的html元素和map中的area(图片热区映射)在点击过后留有默认的蓝色边框,如下图 可以看到,蓝色的边框破坏了页面的整体美感,很多时候我们都是不需要的.通过设置相应的css可以去 ...

  4. PHP字符串中的变量解析

    定义字符串的时候,用单引号或者双引号都是可以的.我个人习惯是用双引号.在输出字符串的时候,若字符串中含有字符串变量,使用单引号和双引号则是有区别的.如下面程序: <?php $website = ...

  5. 存储过程与SQL语句怎么选择

    应用存储过程的优点:1.具有更好的性能存储过程是预编译的,只在创建时进行编译,以后每次执行存储过程都不需再重新编译,而一般 SQL 语句每执行一次就编译一次,因此使用存储过程可以提高数据库执行速度.2 ...

  6. 检测SqlServer服务器性能

    通过性能监视器监视 Avg. Disk Queue Length   小于2 Avg. Disk sec/Read , Avg. Disk sec/Write  小于10ms 可以用数据收集器定时收集 ...

  7. mysql数据安全一之数据恢复案例

    mysql数据安全一之数据恢复案例 --chenjianwen 应用场景:适宜开启binlog 日志功能,定时备份并使用--master-data参数备份,在某个时间点丢失数据,用于数据恢复 开篇总结 ...

  8. [Cpp primer] Library string Type

    In order to use string type, we need to include the following code #include<string> using std: ...

  9. 初识python(python的安装与运行)

    python--“优雅”.“明确”.“简单”的哲学定位 一.python的安装(Windows环境下) 1.在python官网下载安装文件 python的官方网址:https://www.python ...

  10. django之使用jquery完成ajax

    使用Ajax 使用视图通过上下文向模板中传递数据,需要先加载完成模板的静态页面,再执行模型代码,生成最张的html,返回给浏览器,这个过程将页面与数据集成到了一起,扩展性差 改进方案:通过ajax的方 ...