Python Asyncio和标记的HREF
我有一些代码,其中有一些HREF和一些附带的标签。我需要确保标签、HREF和提取HREF的响应都保持关联(例如,列表列表中的列表、元组列表等) 由于Asyncio是异步操作的,如果我理解正确的话,收集的拉取的HREF结果可能会以与发送结果不同的顺序返回。这意味着,如果在返回页面渲染后尝试处理,则渲染页面可能与标签顺序不符。我理解正确吗 例如:Python Asyncio和标记的HREF,python,python-asyncio,Python,Python Asyncio,我有一些代码,其中有一些HREF和一些附带的标签。我需要确保标签、HREF和提取HREF的响应都保持关联(例如,列表列表中的列表、元组列表等) 由于Asyncio是异步操作的,如果我理解正确的话,收集的拉取的HREF结果可能会以与发送结果不同的顺序返回。这意味着,如果在返回页面渲染后尝试处理,则渲染页面可能与标签顺序不符。我理解正确吗 例如: href_list = ['www.google.com', 'www.yahoo.com', 'www.amazon.com'] names_list
href_list = ['www.google.com', 'www.yahoo.com', 'www.amazon.com']
names_list = ['Google','Yahoo','Amazon']
zipped_list = list(zip(href_list,names_list))
async def fetch_href(session, href):
response = await session.request(method='GET', url=href)
return await response.text()
async with aiohttp.ClientSession() as session:
page_results = await asyncio.gather(*(fetch_href(session, href)
for i, href in enumerate([item[0] for item in zipped_list])))
#page_results may have html in a different order than the hrefs and labels in zipped_list
#because of asyncronous behavior of the function (?) e.g:
# page_results == [amazon_html, google_html, yahoo_html]
#if I try to zip with zip_list or components the html results would be out of order with
#hrefs and labels
我的理解是,page_结果
的元素可能与zip_列表
中的hrefs
和名称
的顺序不一致,因为这些单独的请求可能会以不同的顺序返回
保持href、name和page result相互关联的最佳方法是什么
谢谢。您的结果将按照传递给收集的顺序返回。根据“结果值的顺序对应于aws中可等待项的顺序。” 您的结果可能以任何顺序到达,这是正确的,但是,只有在所有协同例程都完成执行后,gather方法才会组装其结果数组。一旦它们完成,它将按照传递协同程序的顺序组合结果,因此,即使网站2首先完成,您也将首先获得网站1,然后获得网站2