【发布时间】:2021-06-08 22:17:46
【问题描述】:
我来自 C# 背景,Python 的 Asyncio 库让我很困惑。
我已经阅读了以下12,但我仍然不清楚 asyncio 的使用。
我正在尝试用python制作一个异步网站scraper。
async def requestPage(url):
request = requests.get(url, headers=headers)
soup = BeautifulSoup(request.content, 'html.parser')
return soup
async def main():
#****** How do I run an async task and store its result to use in another task?
index_soup = asyncio.ensure_future(requestPage(index_url))
res = asyncio.gather(index_soup)
currency_urls = res.select('a[href^="/currencies"]')
print(currency_urls)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
finally:
loop.close()
【问题讨论】:
-
这永远不会真正异步,因为请求不是异步的。您可能需要考虑改用 aiohttp 之类的库。
标签: python python-asyncio