我需要反复解析一个链接内容。同步方式每秒给我 2-3 个响应,我需要更快(是的,我知道,太快也不好)
我找到了一些异步示例,但它们都显示了在解析所有链接后如何处理结果,而我需要在收到后立即解析它,就像这样,但这段代码没有提供任何速度改进:
import aiohttp
import asyncio
import time
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
while True:
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'https://example.com')
print(time.time())
#do_something_with_html(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
请您参考如下方法:
but this code doesn't give any speed improvement
asyncio(以及一般的异步/并发)提高了相互交错的 I/O 事物的速度。
当您所做的一切都是await something 并且您永远不会创建任何并行任务时(使用asyncio.create_task()、asyncio.ensure_future() 等)那么你基本上就是在做经典的同步编程:)
那么,如何使请求更快:
import aiohttp
import asyncio
import time
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def check_link(session):
html = await fetch(session, 'https://example.com')
print(time.time())
#do_something_with_html(html)
async def main():
async with aiohttp.ClientSession() as session:
while True:
asyncio.create_task(check_link(session))
await asyncio.sleep(0.05)
asyncio.run(main())
注意:async with aiohttp.Clientsession() as session: 必须高于(外部)while True: 才能工作。实际上,无论如何,为所有请求使用一个 ClientSession() 是一个很好的做法。
