python并发编程实战(五):python实现生产者、消费者爬虫

1|0多组建的pipline技术架构


2|0生产者消费者爬虫的架构


3|0多进程数据通信的queue.Queue



线程安全:指的是多个线程不会冲突
get和put方法是阻塞的:当里面没有数据的时候,q.get()会卡住,直到里面有了数据把它取出来,q.put()当队列满了以后会卡住,直到有一个空闲的位置才能put进去

4|0代码实现


tmp/blog_spider.py

import requests from bs4 import BeautifulSoup urls = [ f"https://www.cnblogs.com/#p{page}" for page in range(1, 50+1) ] def craw(url): r = requests.get(url) return r.text def parse(html): soup = BeautifulSoup(html, 'html.parser') links = soup.find_all("a", class_="post-item-title") return [(link["href"], link.get_text()) for link in links] if __name__ == '__main__': for result in parse(craw(urls[2])): print(result)

tmp/02.producer_consumer_spider.py

import queue import blog_spider import time, random import threading #生产者 def do_craw(url_queue: queue.Queue, html_queue: queue.Queue): while True: url = url_queue.get() html = blog_spider.craw(url) html_queue.put(html) print(threading.current_thread().name + f" craw {url}", "url_queue.size=", url_queue.qsize()) time.sleep(random.randint(1, 2)) #消费者 def do_parse(html_queue: queue.Queue, fout): while True: html = html_queue.get() results = blog_spider.parse(html) for result in results: fout.write(str(result) + "\n") print(threading.current_thread().name + " results.size", len(results), "html_queue.size=", html_queue.qsize()) time.sleep(random.randint(1, 2)) if __name__ == '__main__': url_queue = queue.Queue() html_queue = queue.Queue() for url in blog_spider.urls: url_queue.put(url) for idx in range(3): t = threading.Thread(target=do_craw, args=(url_queue, html_queue), name=f"craw{idx}") t.start() fout = open("02.data.txt", "w") for idx in range(2): t = threading.Thread(target=do_parse, args=(html_queue, fout), name=f"parse{idx}") t.start()

5|0爬取结果



__EOF__

本文作者cnhkzyy
本文链接https://www.cnblogs.com/my_captain/p/16438467.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   cnhkzyy  阅读(118)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2018-07-02 显性等待的另一种写法
2018-07-02 selenium定位多个嵌套iframe
2017-07-02 《Advanced Bash-scripting Guide》学习(十一):shift的用法
2017-07-02 《Advanced Bash-scripting Guide》学习(十):利用whois查询域名信息
点击右上角即可分享
微信分享提示