多线程生产者消费者模型爬虫

import queue

import requests
from bs4 import BeautifulSoup
import threading
import time
import random def craw(url):
r = requests.get(url=url)
return r.text def parse(html):
soup = BeautifulSoup(html, "html.parser")
links = soup.find_all("a", class_="post-time-title")
return [(link["href"], link.get_test()) for link in links] def do_craw(url_queue: queue.Queue, html_queue: queue.Queue):
while True:
url = url_queue.get()
html = craw(url)
html_queue.put(html)
print(threading.current_thread().name, url)
time.sleep(random.randint(1,2)) def do_parse(html_queue:queue.Queue, f_out):
while True:
html = html_queue.get()
results = parse(html)
for result in results:
f_out.write(str(result) + "\n")
print(threading.current_thread().name, html_queue.qsize())
time.sleep(1) if __name__ == '__main__':
url_queue = queue.Queue()
html_queue = queue.Queue()
for url in ["https://www.cnblogs.com/#p{}".format(i) for i in range(1, 25)]:
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() file = open("02.data.txt", "w")
for idx in range(2):
d = threading.Thread(target=do_parse, args=(html_queue, file), name=f"parse-{idx}")
d.start()

多线程池爬虫

from concurrent.futures import ThreadPoolExecutor, as_completed
import requests
from bs4 import BeautifulSoup spider_url = ["https://www.cnblogs.com/#p{}".format(i) for i in range(1, 25)] def craw(url):
r = requests.get(url=url)
return r.text def parse(html):
soup = BeautifulSoup(html, "html.parser")
links = soup.find_all("a", class_="post-time-title")
return [(link["href"], link.get_test()) for link in links] # craw
with ThreadPoolExecutor() as pool:
htmls = pool.map(craw, spider_url)
htmls = list(zip(spider_url, htmls))
for k, v in htmls:
print(k, len(v)) with ThreadPoolExecutor() as pool:
futures = {}
for url, html in htmls:
future = pool.submit(parse, html)
futures[future] = url # for k, v in futures.items():
# print(v, k.result())
for future in as_completed(futures):
print(futures[future], future.result())

协程

import asyncio
import aiohttp spider_url = ["https://www.cnblogs.com/taozhengquan/p/14966535.html"]*50 # 信号量控制爬虫数量
semaphore = asyncio.Semaphore(10) async def async_craw(url):
async with semaphore:
print("craw url:", url)
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
result = await resp.text()
print(url, len(result)) loop = asyncio.get_event_loop()
tasks = [
loop.create_task(async_craw(item)) for item in spider_url
]
loop.run_until_complete(asyncio.wait(tasks))

Python 多线程、线程池、协程 爬虫的更多相关文章

  1. python之路32 网络并发线程方法 线程池 协程

    多进程实现TCP服务端并发 服务端: import socket from multiprocessing import Process def get_server(): server = sock ...

  2. python进程.线程和协程的总结

    I.进程: II.多线程threading总结 threading用于提供线程相关的操作,线程是应用系统中工作的最小单位(cpu调用的最小单位). Python当前版本的多线程没有实现优先级,线程组, ...

  3. 互斥锁 线程理论 GIL全局解释器锁 死锁现象 信号量 event事件 进程池与线程池 协程实现并发

    目录 互斥锁 multiprocessing Lock类 锁的种类 线程理论 进程和线程对比 开线程的两种方式(类似进程) 方式1 使用Thread()创建线程对象 方式2 重写Thread类run方 ...

  4. 11.python之线程,协程,进程,

    一,进程与线程 1.什么是线程 线程是操作系统能够进行运算调度的最小单位.它被包含在进程之中,是进程中的实际运作单位.一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行 ...

  5. 05网络并发 ( GIL+进程池与线程池+协程+IO模型 )

    目录 05 网络并发 05 网络并发

  6. python全栈开发 * 线程队列 线程池 协程 * 180731

    一.线程队列 队列:1.Queue 先进先出 自带锁 数据安全 from queue import Queue from multiprocessing import Queue (IPC队列)2.L ...

  7. python并发编程-进程池线程池-协程-I/O模型-04

    目录 进程池线程池的使用***** 进程池/线程池的创建和提交回调 验证复用池子里的线程或进程 异步回调机制 通过闭包给回调函数添加额外参数(扩展) 协程*** 概念回顾(协程这里再理一下) 如何实现 ...

  8. python 线程(其他方法,队列,线程池,协程 greenlet模块 gevent模块)

    1.线程的其他方法 from threading import Thread,current_thread import time import threading def f1(n): time.s ...

  9. python简单线程和协程学习

    python中对线程的支持的确不够,不过据说python有足够完备的异步网络框架模块,希望日后能学习到,这里就简单的对python中的线程做个总结 threading库可用来在单独的线程中执行任意的p ...

  10. Day037--Python--线程的其他方法,GIL, 线程事件,队列,线程池,协程

    1. 线程的一些其他方法 threading.current_thread()  # 线程对象 threading.current_thread().getName()  # 线程名称 threadi ...

随机推荐

  1. Python制作词云--stylecloud简单使用

    安装 pip install stylecloud 使用 from stylecloud import gen_stylecloud gen_stylecloud('zhangsan lisi wan ...

  2. 中间件之Mycat

    一.概念 介绍 Mycat是开源的.活跃的.基于Java语言编写的MySQL数据库中间件.可以像使用mysql一样来使用mycat,对于开发人员来说根本感觉不到mycat的存在 Mycat不负责存储数 ...

  3. Mysql之SQL语句初级用法

    前言 本文通过简单的示例去了解Mysql的DDL.DML.DCL的语句用法. 一.DDL语句 DDL(Data Definition Language)语句: 数据定义语言,主要是进行定义/改变表的结 ...

  4. Python3中pip3命令的用法介绍及安装配置

    第一节:pip3是什么?有啥用? pip3:(Python3 Install Package ),这个英文全称是我为了更好的理解这个命令这么叫的,官方没有这对个命令的全称的解释:) python 支持 ...

  5. 【进阶篇】Java 实际开发中积累的几个小技巧(二)

    目录 前言 六.自定义注解 6.1定义注解 6.2切面实现 6.3业务使用 七.抽象类和接口 7.1隔离业务层与 ORM 层 7.2隔离子系统的业务实现 7.3选择对比 文章小结 前言 笔者目前从事一 ...

  6. Pytorch-tensor的分割,属性统计

    1.矩阵的分割 方法:split(分割长度,所分割的维度),split([分割所占的百分比],所分割的维度) a=torch.rand(32,8) aa,bb=a.split(16,dim=0) pr ...

  7. 浅析Golang map的实现原理

    Golang中的map底层使用的数据结构是hash table,基本原理就和基础的散列表一致,重点是Golang在设计中采用了分桶(Bucket),每个桶里面支持多个key-value元素的这种思路, ...

  8. 【hibernate】使用HQL对页面进行时间校验操作(预约)

    [hibernate]使用HQL对页面进行时间校验操作(预约) 预约系统中的时间校验 正好接了一个预约的需求,还需要用java 7和hibernate 1.时间冲突,时间段不能重复,在保存前对数据库进 ...

  9. bilibili 实时平台的架构与实践

    摘要:本文由 bilibili 大数据实时平台负责人郑志升分享,基于对 bilibili 实时计算的痛点分析,详细介绍了 bilibili Saber 实时计算平台架构与实践.本次分享主要围绕以下四个 ...

  10. 用python编写向通信产品发送AT指令的程序实例

    一.安装pyserial包pip install pyserial 二.实例代码 # -*- coding: utf-8 -*- import time import hashlib from ser ...