【发布时间】:2016-06-25 21:54:45
【问题描述】:
在较早的问题中,aiohttp 的一位作者建议使用 Python 3.5 中的新 async with 语法来使用 fetch multiple urls with aiohttp 的方式:
import aiohttp
import asyncio
async def fetch(session, url):
with aiohttp.Timeout(10):
async with session.get(url) as response:
return await response.text()
async def fetch_all(session, urls, loop):
results = await asyncio.wait([loop.create_task(fetch(session, url))
for url in urls])
return results
if __name__ == '__main__':
loop = asyncio.get_event_loop()
# breaks because of the first url
urls = ['http://SDFKHSKHGKLHSKLJHGSDFKSJH.com',
'http://google.com',
'http://twitter.com']
with aiohttp.ClientSession(loop=loop) as session:
the_results = loop.run_until_complete(
fetch_all(session, urls, loop))
# do something with the the_results
但是,当session.get(url) 请求之一中断时(如上所述,因为http://SDFKHSKHGKLHSKLJHGSDFKSJH.com),错误不会得到处理,整个事情都会中断。
我寻找插入有关session.get(url) 结果的测试的方法,例如寻找try ... except ... 或if response.status != 200: 的位置,但我只是不明白如何使用async with,@ 987654332@ 和各种对象。
由于async with 还很新,所以例子不多。如果asyncio 向导可以展示如何做到这一点,这对许多人来说将是非常有帮助的。毕竟,大多数人想要使用asyncio 进行测试的第一件事就是同时获取多个资源。
目标
目标是我们可以检查the_results 并快速查看:
- 此 URL 失败(以及原因:状态代码,可能是异常名称),或者
- 这个网址有效,这是一个有用的响应对象
【问题讨论】:
标签: python python-3.x web-scraping python-asyncio aiohttp