文章目录

  • 一. 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()

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

  1. Android实战——jsoup实现网络爬虫,糗事百科项目的起步

    Android实战--jsoup实现网络爬虫,爬糗事百科主界面 本篇文章包括以下内容: 前言 jsoup的简介 jsoup的配置 jsoup的使用 结语 前言 对于Android初学者想要做项目时,最 ...

  2. python爬虫案例——糗事百科数据采集

    全栈工程师开发手册 (作者:栾鹏) python教程全解 python爬虫案例--糗事百科数据采集 通过python实现糗事百科页面的内容采集是相对来说比较容易的,因为糗事百科不需要登陆,不需要coo ...

  3. 网络爬虫--14.【糗事百科实战】

    文章目录 一. 要求 二. 参考代码 一. 要求 爬取糗事百科段子,假设页面的URL是 http://www.qiushibaike.com/8hr/page/1 使用requests获取页面信息,用 ...

  4. python爬虫之糗事百科

    历经1个星期的实践,终于把python爬虫的第一个实践项目完成了,此时此刻,心里有的只能用兴奋来形容,后续将继续加工,把这个做成一个小文件,发给同学,能够在cmd中运行的文件.简化版程序,即单单爬取页 ...

  5. 爬虫 | urllib入门+糗事百科实战

    所谓爬虫(crawler),是指一只小虫子,在网络中爬行,见到有用的东西就会把它拿下来,是我们获取信息的一个重要途径.平常使用的浏览器,它的背后就是一个巨大的爬虫框架,输入我们想要查找的信息,帮我们爬 ...

  6. 网络爬虫---爬取糗事百科段子实战

    Python网络爬虫 1.知识要求 掌握python基础语法 熟悉urllib模块知识 熟悉get方法 会使用浏览器伪装技术 如果您对相关知识遗忘了,可以点上面的相关知识链接,熟悉一下. 2.爬取糗事 ...

  7. python多线程爬取段子_Python爬虫实例-多线程爬虫糗事百科搞笑内涵段子

    学习爬虫,其乐无穷! 今天给大家带来一个爬虫案例,爬取糗事百科搞笑内涵段子. 爬取糗事百科段⼦,假设⻚⾯的 URL 是:http://www.qiushibaike.com/8hr/page/1 一. ...

  8. Python爬虫实战(1):爬取糗事百科段子

    Python爬虫入门(1):综述 Python爬虫入门(2):爬虫基础了解 Python爬虫入门(3):Urllib库的基本使用 Python爬虫入门(4):Urllib库的高级用法 Python爬虫 ...

  9. python爬虫经典段子_Python爬虫实战(1):爬取糗事百科段子

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

最新文章

  1. Spring配置文件中注入复杂类型属性
  2. 端口扫描系统实践心得
  3. Apache2 httpd.conf 配置详解(一)
  4. 【实战 Ids4】║ 客户端、服务端、授权中心全线打通!
  5. webrender 查看是否开启_查看端口是否启用
  6. abrtd:Executable ‘some execution‘ doesn‘t belong to any package and ProcessUnpackaged is set to ‘no‘
  7. 【深度学习】生成对抗网络(GAN)的tensorflow实现
  8. 操作系统进程调度算法总结
  9. ‘文件夹正在使用‘解决方案
  10. 2019-01-01T00:00:00.000Z 这种时间日期类型格式是属于:格林尼治时间
  11. vs各个版本下载路径
  12. PAT_乙级_1004_筱筱
  13. CSP第二轮比赛注意事项
  14. RR正显著-不显著 -负显著
  15. 视频播放密码/视频加密功能
  16. 【通信协议】1-Wire 单总线
  17. C++学习资料和视频
  18. ShaderJoy —— 仿抖音的十字星光效果 【GLSL】
  19. KVM内存管理(一)—— 设置基本参数
  20. 软件工程基础知识--认识软件工程

热门文章

  1. codeforces 122A-C语言解题报告
  2. Idea中搭建Resin运行环境(Mac)
  3. Java提高篇 ——Java注解
  4. linux/unix核心设计思想
  5. AMD GPU+VS2010的OpenCL配置
  6. 中国人为什么学不会英语
  7. SpringMvc 注解 @InitBinder 表单多对象精准绑定接收
  8. 注解驱动的 Spring cache 缓存介绍
  9. jQuery上传插件Uploadify使用Demo、本地上传(ssm框架下)
  10. ssm(springMVC + spring+MyBatis) 小例