python爬虫3-多进程多线程协程

news/2024/7/7 21:26:51/文章来源:https://www.cnblogs.com/noahze/p/18284627

多进程和多线程

from multiprocessing import Process
import threadingdef process_worker():for i in range(200):print(f"Process worker {i}")def thread_worker():for i in range(200):print(f"Thread worker {i}")if __name__ == '__main__':# 创建并启动一个进程p = Process(target=process_worker)p.start()# p.join() # 阻塞主线程(或主进程),直到被调用的线程(或进程)完成执行。# 创建并启动一个线程t = threading.Thread(target=thread_worker)t.start()# t.join() # 阻塞主线程(或主进程),直到被调用的线程(或进程)完成执行。for i in range(200):print(f"主进程 {i}")

线程池和进程池

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import timedef io_task(n):print(f'IO Task {n} starting')time.sleep(2)print(f'IO Task {n} finished')def cpu_task(n):print(f'CPU Task {n} starting')result = sum(i*i for i in range(10**6))print(f'CPU Task {n} finished with result {result}')if __name__ == '__main__':with ThreadPoolExecutor(max_workers=2) as thread_pool, ProcessPoolExecutor(max_workers=2) as process_pool:thread_futures = [thread_pool.submit(io_task, i) for i in range(4)]     # 循环四次(从 i=0 到 i=3),每次循环调用 io_task 函数并传递当前的循环计数 i 作为参数。process_futures = [process_pool.submit(cpu_task, i) for i in range(4)]  # 循环四次(从 i=0 到 i=3),每次循环调用 cpu_task 函数并传递当前的循环计数 i 作为参数。print("Main thread continues")

豆瓣实例

import requests
from lxml import etree
import re
import csv
from concurrent.futures import ThreadPoolExecutorcsvfile = open("douban4.csv",mode="w",encoding="utf-8")
csvwriter = csv.writer(csvfile)def download_one_page(url):# 网页源码# 头部信息headers = {'User-Agent': 'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',}resp = requests.get(url,headers=headers)html = etree.HTML(resp.text)# 使用 XPath 选取所有 title 元素的文本内容lis = html.xpath('//*[@id="content"]/div/div[1]/ol/li')for li in lis:name = li.xpath("./div/div[2]/div[1]/a/span[1]/text()")[0]  # 名字year = li.xpath("./div/div[2]/div[2]/p[1]/text()[2]")[0]  # 年份rating = li.xpath("./div/div[2]/div[2]/div/span[2]/text()")[0]  # 评分year = re.findall(r'\b\d{4}\b', year)[0]  # 对年份进行处理# 保存为csv文件csvwriter.writerow([name, year, rating])print(url,"提取完毕")if __name__ == '__main__':with ThreadPoolExecutor(3) as thread_pool:for i in range(10):thread_pool.submit(download_one_page,f'http://movie.douban.com/top250?start={i*25}&filter=')print("over")

协程

协程(coroutine)是一种用于并发编程的构造,允许你在等待某些操作完成时进行其他工作。协程在处理 I/O 绑定任务(如网络请求或文件读取)时特别有用,因为它们可以在一个任务等待完成时切换到另一个任务。

实例

import asyncioasync def say(what, when):      # async 关键字 用来定义一个协程.await asyncio.sleep(when)   # await 关键字 用来挂起阻塞方法的执行。print(what)async def main():# 并行执行多个协程await asyncio.gather(say("First", 2),say("Second", 1),say("Third", 3))if __name__ == '__main__':asyncio.run(main()) #运行协程

异步爬取图片

import asyncio
import aiohttp
import osurls = ["https://p0.ssl.qhimgs1.com/sdr/400__/t01c3a6a8abd00f35a4.jpg","https://p2.ssl.qhimgs1.com/sdr/400__/t01f2bf1a12bb90de88.jpg","https://p1.ssl.qhimgs1.com/sdr/400__/t0101cc32a15d91a3f7.jpg"
]async def aiodownload(url):name = url.rsplit("/", 1)[1]  # 提取文件名async with aiohttp.ClientSession() as session:async with session.get(url) as resp:with open(name, mode="wb") as f:f.write(await resp.content.read())  # 读取内容为异步,需要awaitprint(name, "over")async def main():tasks = [aiodownload(url) for url in urls]await asyncio.gather(*tasks)  # 使用 asyncio.gather() 代替 asyncio.wait()if __name__ == '__main__':# 在 Windows 上使用 SelectorEventLoopif os.name == 'nt':asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())try:asyncio.run(main())  # 运行协程except RuntimeError as e:if str(e) == "Event loop is closed":loop = asyncio.new_event_loop()asyncio.set_event_loop(loop)loop.run_until_complete(main())

百度西游记异步爬取

import requests
import asyncio
import aiohttp
import aiofiles
import os
import jsonasync def aiodownload(cid, b_id, title):# 拼接urldata = {"book_id": b_id,"cid": f"{b_id}|{cid}","need_bookinfo": 1}data = json.dumps(data)url = f"https://dushu.baidu.com/api/pc/getChapterContent?data={data}"async with aiohttp.ClientSession() as session:async with session.get(url) as resp:# 异步获取网页数据dic = await resp.json()if 'data' in dic and 'novel' in dic['data'] and 'content' in dic['data']['novel']:content = dic['data']['novel']['content']# 异步写入文件async with aiofiles.open(os.path.join('novel', title + '.txt'), mode="w", encoding='utf-8') as f:await f.write(content)else:print(f"Failed to get content for chapter {title}")# 实现同步获取目录
async def getCatalog(url, b_id):resp = requests.get(url)dic = resp.json()tasks = []# 获取目录并添加协程任务for item in dic['data']['novel']['items']:title = item['title']cid = item['cid']# 准备异步任务tasks.append(aiodownload(cid, b_id, title))# 异步执行任务await asyncio.gather(*tasks)if __name__ == '__main__':b_id = "4306063500"url = f'https://dushu.baidu.com/api/pc/getCatalog?data={{"book_id":"{b_id}"}}'# 创建novel目录if not os.path.exists('novel'):os.makedirs('novel')# 在 Windows 上使用 SelectorEventLoopif os.name == 'nt':asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())try:asyncio.run(getCatalog(url, b_id))except RuntimeError as e:if str(e) == "Event loop is closed":loop = asyncio.new_event_loop()asyncio.set_event_loop(loop)loop.run_until_complete(getCatalog(url, b_id))

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

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

相关文章

比赛获奖的武林秘籍:01 如何看待当代大学生竞赛中“卷”“祖传老项目”“找关系”的现象?

本文主要分析了大学生电子计算机类比赛中“卷”“祖传老项目”“找关系”的现象,结合自身实践经验,给出了相应的解决方案。比赛获奖的武林秘籍:01 如何看待当代大学生竞赛中“卷”“祖传老项目”“找关系”的现象? 正文 目前现状 对于大部分的比赛小白来说,对当前比赛的现…

2024.7.4 鲜花

今日推歌 natural Will you hold the line. 只有你还没有放弃。 When every one of them is giving up or giving in, tell me. 当其他所有人都停止了尝试,被挫折磨尽了希望。 In this house of mine,Nothing ever comes without a consequence or cost, tell me. 我所在之处,…

【python+selenium的web自动化】—— 控制浏览器

前言: 需本教程以Edge做测试,且谷歌、火狐等浏览器的逻辑都一样需要使用 selenium 模块操作 Edge 浏览器。 一、先通过pip install 模块 把selenium模块安装了,可以加一个中国源提升速度。pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple二、需要下载Edg…

Python自动化之控制浏览器

前言: 需本教程以Edge做测试,且谷歌、火狐等浏览器的逻辑都一样需要使用 selenium 模块操作 Edge 浏览器。 一、先通过pip install 模块 把selenium模块安装了,可以加一个中国源提升速度。pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple二、需要下载Edg…

设计模式-设计原则与设计模式总结

设计原则,是设计模式的基础。在实际开发中,并不是一定要求所有代码都遵循设计原则,我们需要综合考虑人力、时间、成本、质量,不是可以追求完美,要在设当的场景遵循合适的设计原则,体现的是一种平衡取舍,帮助我们设计出更加优雅的代码结构。 设计模式(Design Pattern)是前…

mirai Bot初始化配置

RT其实本来我的bot已经因为自己手贱登陆qq nt直接报废了,但是论坛里有佬提供了新的协议库,那这不赶紧复活bot都对不起这个新的协议库。 本文写于2024年7月4日19:20:21,可能随着时间久远而无法实现功能。由于存在下载障碍,所以这里也搞了个存档,本帖中的相关标星*资源无法下…

量化曲线的平滑程度

思路 1. 对原始数据一阶求导,得到一阶导数数组。 2. 对一阶导数数组求标准差。导数的标准差提供了导数值的波动性,标准差越小,曲线越平滑。 平滑曲线import numpy as np import matplotlib.pyplot as plt from matplotlib import font_manager fname="/usr/local/pytho…

Android常见错误

错误1 A problem occurred configuring root project ����ʶ��. > Could not resolve all files for configuration :classpath.> Could not resolve com.android.tools.build:gradle:8.4.0.Required by:project : > com.android.application:com.android.appli…

MyBatis中的Where标签:提升你的SQL查询效率

哈喽,大家好,我是木头左!理解MyBatis的Where标签 MyBatis是一款优秀的持久层框架,它提供了许多强大的标签来帮助编写更优雅、高效的SQL语句。其中,<where>标签是使用频率极高的一个,它能够自动处理查询条件,使得的SQL语句更加简洁和高效。在这篇文章中,将深入探讨…

Java中的JSON神器,如何轻松玩转复杂数据结构

哈喽,大家好,我是木头左!一、揭秘JSON世界的基石 在Java的世界中,JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它基于文本,易于阅读和编写,同时也易于机器解析和生成。JSON在日常开发中的应用非常广泛,无论是前后端的数据交互,还是配置文件的读取,…

《Python 第三方模块包安装指南》

在 Python 编程中,第三方模块包极大地丰富了其功能,让我们能够更高效地完成各种任务。下面将为您详细介绍如何安装 Python 的第三方模块包。 一、使用 pip 命令安装 pip 是 Python 的包管理工具,大多数情况下,我们可以通过以下命令来安装第三方模块包:pip install 模块包名…

巴图自动化Modbus转PN网关模块连智能仪表与PLC通讯

通过巴图自动化Modbus转Profinet协议网关模块,实现PLC对仪表设备的远程监控和数据传输,提高生产效率和运行稳定性。巴图自动化Modbus转Profinet协议转换BT-MDPN100网关模块的主要功能是实现Modbus协议和Profinet协议之间的转换和通信。Modbus 转 Profinet协议网关模块集成了M…

一文搞懂到底什么是 AQS

日常开发中,我们经常使用锁或者其他同步器来控制并发,那么它们的基础框架是什么呢?如何实现的同步功能呢?本文将详细用白话讲解构建锁和同步器的基础框架--AQS,并根据源码分析其原理。前言 日常开发中,我们经常使用锁或者其他同步器来控制并发,那么它们的基础框架是什么…

flutter状态管理 provider使用

provider是flutter官方推荐的状态管理插件,是基于InheritedWidget实现的。 下面我们来讲一个provider的使用方法。 1.在pubspec.yaml文件中添加 provider: ^6.1.2 开发文档:https://pub-web.flutter-io.cn/packages/provider 可以查看使用方法和最新版本号。 添加完成后…

企业数字化转型:顶层规划方法

随着数字化时代的到来,发生了以数字化、智能化为典型特征的新一轮科技革命,各行各业利用互联网、大数据、云计算、人工智能、区块链技术对传统产业进行全方位、全链条改造,实施“上云用数赋智”行动,全面推进各行业数字化转型。数字经济的大门已然开启,数字经济顶层战略规…

Nuxt3 的生命周期和钩子函数(十)

摘要:本文详细介绍了Nuxt3框架中的五个webpack钩子函数:webpack:configResolved用于在webpack配置解析后读取和修改配置;webpack:compile在编译开始前调用,可修改编译选项;webpack:compiled在编译完成后调用,可处理编译结果;webpack:change在开发模式下文件变化时触发,…

Jenkins汉化

1、Jenkins版本:版本2.426.3) Manage Jenkins->选择Plugins->切换到Availabled plugin->搜索local,然后选中安装,如下图所示 2、安装完成后重启Jenkins,汉化完成。如下图所示 像个小学生一样努力学习

模拟集成电路设计系列博客——9.1 比较器

模拟集成电路设计 9.1 比较器 比较器可能是继放大器之后第二常用的电路元件,比较器用于判断一个信号是否大于或小于零,或者比较一个信号是否大于另一个。如我们之前的章节所见,比较器在ADC中非常常用。在其他的应用中也经常出现比较器,例如数据传输,开关电源稳压器等等。 …

prufer序列

prufer序列用途: 将带标号的树用唯一的整数序列表示出来,证明凯莱公式。构造方法:每次选择一个编号最小的叶结点并删掉它,然后在序列中记录下它连接到的那个结点。重复\(n-2\)次后就只剩下两个结点,算法结束。 举个栗子(本图来自baoziwu2,侵删)显然可以有一个用堆做的方法,…

【冷启动#2】实用的springboot tutorial入门demo

跟着官方文档熟悉一遍创建spring工程的步骤 https://spring.io/guides/gs/spring-boot https://juejin.cn/post/7077958723829760008 demo简介 整个demo的预期目标是: 管理一堆玩家的数据,数据库使用的是现成的我们虚拟机上安装的MySQL 项目结构参考 主要工作:创建并熟悉spr…