0
点赞
收藏
分享

微信扫一扫

python单线程+异步协程简单使用

高性能异步爬虫:

异步爬虫的方式:

3、单线程+异步协程(推荐)

event_loop:事件循环,相当于一个无限循环,可以把一些函数注册到这个事件循环上,当满足某些条件的时候,函数就会被循环执行。

coroutine:协程对象,可以将协程对象注册到事件循环中,它被事件循环调用。可以使用async关键字来定义一个方法,这个方法在调用时不会立即被执行,而是返回一个协程对象。

task:任务,它是协程对象的进一步封装,包含了任务的各个状态。

future:代表将来执行或还没有执行的任务,实际上和task没有本质区别。

async:定义一个协程。

await:用来挂起阻塞方法的执行。


简单例子:

# coding:utf-8
import time
import asyncio

async def request(url):
print("正在下载", url)
# 在异步协程中如果出现了同步模块相关的代码,那么就无法实现异步
# time.sleep(2)
# 当在asyncio中遇到阻塞操作时必须进行手动挂起
await asyncio.sleep(2)
print("下载完毕", url)

start = time.time()
urls = [
"www.baidu.com",
"www.sougou.com",
"www.163.com"
]

# 任务列表:存放多个任务对象
stasks = []
for url in urls:
c = request(url)
task = asyncio.ensure_future(c)
stasks.append(task)

loop = asyncio.get_event_loop()
# 需要将任务列表封装到wait中
loop.run_until_complete(asyncio.wait(stasks))

print(time.time()-start)

python单线程+异步协程简单使用_apache

python单线程+异步协程简单使用_封装_02


使用单线程+协程应用到实际案例:

# coding:utf-8
import time
import asyncio
import aiohttp

headers = {
"User-Agent": "Mozilla/5.0(Windows NT 6.1;WOW64) AppleWebKit/537.36(KABUL, like Gecko) "
"Chrome/86.0.4240.198Safari/537.36 "
}

async def get_page(url):
print("正在下载", url)
# 在异步协程中如果出现了同步模块相关的代码,那么就无法实现异步
# time.sleep(2)
# 当在asyncio中遇到阻塞操作时必须进行手动挂起
async with aiohttp.ClientSession() as session:
# get(),post()
# headers,params/data,proxy="http://ip:port"
async with await session.get(url,headers=headers) as response:
# text()返回字符串形式的响应数据
# read()返回二进制形式的响应数据
# json()返回的就是json对象
# 注意:获取响应数据操作之前一定要使用await进行手动挂起
page_content = await response.read()
title = url.split("/")[-1]
with open(f"{title}","wb") as f:
f.write(page_content)

print("下载完毕", url)

start = time.time()
urls = [
'https://mirrors.tuna.tsinghua.edu.cn/apache/accumulo/1.10.2/accumulo-1.10.2-bin.tar.gz',
'https://mirrors.tuna.tsinghua.edu.cn/apache/accumulo/2.1.0/accumulo-2.1.0-bin.tar.gz',
'https://mirrors.tuna.tsinghua.edu.cn/apache/activemq/5.16.5/apache-activemq-5.16.5-bin.zip'
]

# 任务列表:存放多个任务对象
stasks = []
for url in urls:
c = get_page(url)
task = asyncio.ensure_future(c)
stasks.append(task)

loop = asyncio.get_event_loop()
# 需要将任务列表封装到wait中
loop.run_until_complete(asyncio.wait(stasks))

print("总耗时:",time.time()-start)

python单线程+异步协程简单使用_apache_03

python单线程+异步协程简单使用_事件循环_04

python单线程+异步协程简单使用_事件循环_05


举报

相关推荐

0 条评论