网络爬虫--15.【糗事百科实战】多线程实现

文章目录

  • 一. Queue(队列对象)
  • 二. 多线程示意图
  • 三. 代码示例

一. Queue(队列对象)

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

python下多线程的思考

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

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

  2. 包中的常用方法:
    Queue.qsize() 返回队列的大小
    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
import json
from queue import Queue
import threadingclass Qiubai:def __init__(self):self.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWeb\Kit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"}self.url_queue = Queue()   #实例化三个队列,用来存放内容self.html_queue =Queue()self.content_queue = Queue()def get_total_url(self):'''获取了所有的页面url,并且返回urllistreturn :list'''url_temp = 'https://www.qiushibaike.com/8hr/page/{}/'# url_list = []for i in range(1,36):# url_list.append(url_temp.format(i))self.url_queue.put(url_temp.format(i))def parse_url(self):'''一个发送请求,获取响应,同时etree处理html'''while self.url_queue.not_empty:url = self.url_queue.get()print("parsing url:",url)response = requests.get(url,headers=self.headers,timeout=10) #发送请求html = response.content.decode() #获取html字符串html = etree.HTML(html) #获取element 类型的htmlself.html_queue.put(html)self.url_queue.task_done()def get_content(self):''':param url::return: 一个list,包含一个url对应页面的所有段子的所有内容的列表'''while self.html_queue.not_empty:html = self.html_queue.get()total_div = html.xpath('//div[@class="article block untagged mb15"]') #返回divelememtn的一个列表items = []for i in total_div: #遍历div标枪,获取糗事百科每条的内容的全部信息author_img = i.xpath('./div[@class="author clearfix"]/a[1]/img/@src')author_img = "https:" + author_img[0] if len(author_img) > 0 else Noneauthor_name = i.xpath('./div[@class="author clearfix"]/a[2]/h2/text()')author_name = author_name[0] if len(author_name) > 0 else Noneauthor_href = i.xpath('./div[@class="author clearfix"]/a[1]/@href')author_href = "https://www.qiushibaike.com" + author_href[0] if len(author_href) > 0 else Noneauthor_gender = i.xpath('./div[@class="author clearfix"]//div/@class')author_gender = author_gender[0].split(" ")[-1].replace("Icon", "") if len(author_gender) > 0 else Noneauthor_age = i.xpath('./div[@class="author clearfix"]//div/text()')author_age = author_age[0] if len(author_age) > 0 else Nonecontent = i.xpath('./a[@class="contentHerf"]/div/span/text()')content_vote = i.xpath('./div[@class="stats"]/span[1]/i/text()')content_vote = content_vote[0] if len(content_vote) > 0 else Nonecontent_comment_numbers = i.xpath('./div[@class="stats"]/span[2]/a/i/text()')content_comment_numbers = content_comment_numbers[0] if len(content_comment_numbers) > 0 else Nonehot_comment_author = i.xpath('./a[@class="indexGodCmt"]/div/span[last()]/text()')hot_comment_author = hot_comment_author[0] if len(hot_comment_author) > 0 else Nonehot_comment = i.xpath('./a[@class="indexGodCmt"]/div/div/text()')hot_comment = hot_comment[0].replace("\n:", "").replace("\n", "") if len(hot_comment) > 0 else Nonehot_comment_like_num = i.xpath('./a[@class="indexGodCmt"]/div/div/div/text()')hot_comment_like_num = hot_comment_like_num[-1].replace("\n", "") if len(hot_comment_like_num) > 0 else Noneitem = dict(author_name=author_name,author_img=author_img,author_href=author_href,author_gender=author_gender,author_age=author_age,content=content,content_vote=content_vote,content_comment_numbers=content_comment_numbers,hot_comment=hot_comment,hot_comment_author=hot_comment_author,hot_comment_like_num=hot_comment_like_num)items.append(item)self.content_queue.put(items)self.html_queue.task_done()  #task_done的时候,队列计数减一def save_items(self):'''保存items:param items:列表'''while self.content_queue.not_empty:items = self.content_queue.get()f = open("qiubai.txt","a")for i in items:json.dump(i,f,ensure_ascii=False,indent=2)# f.write(json.dumps(i))f.close()self.content_queue.task_done()def run(self):# 1.获取url list# url_list = self.get_total_url()thread_list = []thread_url = threading.Thread(target=self.get_total_url)thread_list.append(thread_url)#发送网络请求for i in range(10):thread_parse = threading.Thread(target=self.parse_url)thread_list.append(thread_parse)#提取数据thread_get_content = threading.Thread(target=self.get_content)thread_list.append(thread_get_content)#保存thread_save = threading.Thread(target=self.save_items)thread_list.append(thread_save)for t in thread_list:t.setDaemon(True)  #为每个进程设置为后台进程,效果是主进程退出子进程也会退出t.start()          #为了解决程序结束无法退出的问题## for t in thread_list:#     t.join()self.url_queue.join()   #让主线程等待,所有的队列为空的时候才能退出self.html_queue.join()self.content_queue.join()if __name__ == "__main__":qiubai = Qiubai()qiubai.run()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/451996.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

浅谈:国内软件公司为何无法做大做强?

纵览,国内比较大的软件公司(以下统一简称"国软"),清一色都是做政府项目的(他们能做大的原因我就不用说了吧),真正能做大的国软又有几家呢?这是为什么呢? 今天风吹就给大家简单分析下: 1."作坊"式管理 "作坊"往往是效率最高的,国软几乎都是从作…

Java SE、Java EE、Java ME三者的区别

说得简单点 Java SE 是做电脑上运行的软件。 Java EE 是用来做网站的-(我们常见的JSP技术) Java ME 是做手机软件的。 1. Java SE(Java Platform,Standard Edition)。Java SE 以前称为 J2SE。它允许开发和部署在桌面、…

FileBeats安装

FileBeats安装 FileBeats官方下载链接: https://www.elastic.co/downloads/beats/filebeat 也可以直接使用以下命令下载(文章下载目录一概为/home/tools, 解压后文件夹放到 /home/apps下) wget https://artifacts.elastic.co/downloads/beats…

《程序员代码面试指南》第三章 二叉树问题 二叉树节点间的最大距离问题

题目 二叉树节点间的最大距离问题 java代码 package com.lizhouwei.chapter3;/*** Description:二叉树节点间的最大距离问题* Author: lizhouwei* CreateDate: 2018/4/16 19:33* Modify by:* ModifyDate:*/ public class Chapter3_20 {public int maxDistance(Node head) {int[…

MySQL中函数CONCAT及GROUP_CONCAT 对应oracle中的wm_concat

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。 一、CONCAT()函数 CONCAT()函数用于将多个字符串连接成一个字符串。 使用数据表Info作为…

网络爬虫--16.BeautifulSoup4

文章目录一. BeautifulSoup4二. 解析实例三. 四大对象种类1. Tag2. NavigableString3. BeautifulSoup4. Comment四. 遍历文档树1.直接子节点 :.contents .children 属性1). .contents2). .children2. 所有子孙节点: .descendants 属性3. 节点内容: .string 属性五. …

Intel MKL 多线程设置

对于多核程序,多线程对于程序的性能至关重要。 下面,我们将对Intel MKL 有关多线程方面的设置做一些介绍: 我们提到MKL 支持多线程,它包括的两个概念: 1>MKL 是线程安全的: MKL在设计时,就保…

【LA3415 训练指南】保守的老师 【二分图最大独立集,最小割】

题意 Frank是一个思想有些保守的高中老师。有一次,他需要带一些学生出去旅行,但又怕其中一些学生在旅行中萌生爱意。为了降低这种事情发生的概率,他决定确保带出去的任意两个学生至少要满足下面四条中的一条。 1.身高相差大于40厘米 2.性别相…

行车记录仪稳定方案:TC358778XBG:RGB转MIPI DSI芯片,M-Star标配IC

原厂:Toshiba型号:TC358778XBG功能:TC358778XBG是一颗将RGB信号转换成MIPI DSI的芯片,最高分辨率支持到1920x1200,其应用图如下:产品特征:MIPI接口:(1)、支持…

java.sql.SQLException: 无法转换为内部表示之解决

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。 这个错是因为 数据库中字段类型和程序中该字段类型不一致。 比如程序将某字段当做Integer类型, 而数据库存储又使用另外一…

网络爬虫--17.【BeautifuSoup4实战】爬取腾讯社招

文章目录一.要求二.代码示例一.要求 以腾讯社招页面来做演示:http://hr.tencent.com/position.php?&start10#a 使用BeautifuSoup4解析器,将招聘网页上的职位名称、职位类别、招聘人数、工作地点、发布时间,以及每个职位详情的点击链接…

public static void main(String[] args)的理解

public:权限修饰符,权限最大。static:随着MianDemo类的加载而加载,消失而消失。void: 没有返回值main: 函数名,jvm识别的特殊函数名(String[] args):定义了一个字符串数组参数。这个字符串数组是保存运行main函数时输入的参数的

Miller-Rabin素数测试

Miller-Rabin素数测试 给出一个小于1e18的数,问它是否为质数?不超过50组询问。hihocoder 我是真的菜,为了不误导他人,本篇仅供个人使用。 首先,一个1e18的数,朴素\(O(\sqrt{n})\)素数判定肯定爆炸。怎么办呢…

throws Exception的意思

在方法声明部分使用,表示该方法可能产生此异常,如果在方法声明处使用了throws声明异常,则该方法产生异常也不必捕获,会直接把异常抛出到调用该方法的地方。

java list按照元素对象的指定多个字段属性进行排序

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。 直接提取重点代码: /*** 把结果集合按时间字段排序,内部类重写排序规则:* param list* return*/priv…

网络爬虫--18.python中的GIL(全局解释器锁)、多线程、多进程、并发、并行

参考文献: python的GIL、多线程、多进程 并发和并行的区别? GIL(全局解释器锁)一看就懂的解释! 多谢作者分享!

Socket和ServerSocket

对于即时类应用或者即时类的游戏,HTTP协议很多时候无法满足于我们的需求。这会,Socket对于我们来说就非常实用了。下面是本次学习的笔记。主要分异常类型、交互原理、Socket、ServerSocket、多线程这几个方面阐述。异常类型在了解Socket的内容之前&#…

彻底搞清楚Android中的 Attr

版权声明:本文为sydMobile原创文章,转载请务必注明出处! https://blog.csdn.net/sydMobile/article/details/79978187 相信这个词对于Android开发者来说十分熟悉了,那么你对他到底有多了解呢? 回忆起我刚开始接触Andr…

D. Relatively Prime Graph

Lets call an undirected graph G(V,E)G(V,E) relatively prime if and only if for each edge (v,u)∈E(v,u)∈E GCD(v,u)1GCD(v,u)1 (the greatest common divisor of vv and uu is 11). If there is no edge between some pair of vertices vv and uu then the value of GC…

解决 : org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。 报错: org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.tanj.mapper.SendDeta…