当前位置: 代码迷 >> 综合 >> Python爬虫 协程 greenlet yield asyncio asyncawait
  详细解决方案

Python爬虫 协程 greenlet yield asyncio asyncawait

热度:65   发布时间:2023-12-13 18:46:00.0

tornado、fastapi、Django 3.x、agsi、aiohttp等框架都在异步(趋势) ====>提升性能

协程

协程不是计算机提供的,计算机只有进程和线程,是程序员人为创造的。

协程也称微线程,用户态上下文切换的一种技术。

通过一个线程实现代码块相互切换执行。

import timedef func1():print(1)time.sleep(2)print(2)def func2():print(3)time.sleep(2)print(4)func1()
func2()

按意愿执行func1的一段代码,之后执行func2,在执行func1…来回执行

实现方法

greenlet

比较早期的模块

pip install greenlet

下载报错的话,就下载链接里的对应版本
https://www.lfd.uci.edu/~gohlke/pythonlibs/#greenlet

pip install 下载的文件绝对路径(直接拖进去)

案例:

from greenlet import greenletdef func1():print(1)gr2.switch() # 执行func2print(2)gr2.switch() # 执行func2def func2():print(3)gr1.switch() # 执行func1print(4)gr1 = greenlet(func1)
gr2 = greenlet(func2)
gr1.switch() # 执行func1

在这里插入图片描述

yield 关键字

yield是生成器,具有保存状态,切换到其他函数去执行。
作为了解,实际中没什么意义

def func1():yield 1yield from func2()yield 2def func2():yield 3yield 4f1 = func1()
for item in f1:print(item)

在这里插入图片描述

asyncio装饰器(py3.4)

asycnio为python内置模块
遇到io阻塞会自动切换,之前的都是人为控制切换
案例,稍后会详细介绍:

import asyncio@asyncio.coroutine
def func1():print(1)yield from asyncio.sleep(2)print(2)@asyncio.coroutine
def func2():print(3)yield from asyncio.sleep(2)print(4)task = [asyncio.ensure_future(func1()),asyncio.ensure_future(func2())
]loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(task))

在这里插入图片描述

async & await关键字(py3.5)

目前最主流,官方相对推荐的。python 3.5
是基于asyncio 实现的,底层是一样的,对代码操作进行简化。

import asyncioasync def func1():print(1)await asyncio.sleep(2)print(2)async def func2():print(3)await asyncio.sleep(2)print(4)task = [asyncio.ensure_future(func1()),asyncio.ensure_future(func2())
]loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(task))

意义

一个线程中,如果遇到IO等待时间,线程不会等待,利用空闲的时间去执行其他事。
利用io等待的时间,去执行其他事。

对比案例

下载压缩包
1、普通方式(同步)

import requestsdef get_content(url):content = requests.get(url=url, headers=headers).contentreturn contentdef parse_content(content):print(len(content))if __name__ == "__main__":headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'}url_list = ['https://downsc.chinaz.net/Files/DownLoad/moban/202012/moban5094.rar','https://downsc.chinaz.net/Files/DownLoad/moban/202012/moban5093.rar','https://downsc.chinaz.net/Files/DownLoad/moban/202012/moban5089.rar']for url in url_list:content = get_content(url)parse_content(content)print('over')

在这里插入图片描述
2、协程方式 (异步)

安装aiohttp mokjai

pip install aiohttp
import aiohttp
import asyncioasync def get_content(session, url):file_name = url.split('/')[-1]print('开始下载 '+file_name)async with session.get(url, verify_ssl=False) as response:content = await response.content.read()with open('./异步/协程/'+file_name, 'wb') as fp:fp.write(content)print('下载完成 '+file_name)async def main():async with aiohttp.ClientSession() as session:url_list = ['https://downsc.chinaz.net/Files/DownLoad/moban/202012/moban5094.rar','https://downsc.chinaz.net/Files/DownLoad/moban/202012/moban5093.rar','https://downsc.chinaz.net/Files/DownLoad/moban/202012/moban5089.rar']tasks = [asyncio.create_task(get_content(session, url))for url in url_list]await asyncio.wait(tasks)if __name__ == "__main__":asyncio.run(main())

在这里插入图片描述

  相关解决方案