起因是我要用到协程去批量验证多个 http 地址情况:当前 url 地址 ,http 状态 ,title
import asyncio,aiohttp from bs4 import BeautifulSoup res=[] async def fetch_async(url): async with aiohttp.ClientSession() as session: async with session.get(url) as resp: url=resp.url status=resp.status text=await resp.read() soup = BeautifulSoup(text, 'lxml') title=soup.title.string print(url,status,title) #res.append(url,status,title) tasks = [fetch_async('http://www.baidu.com/'), fetch_async('https://www.v2ex.com')] event_loop = asyncio.get_event_loop() results = event_loop.run_until_complete(asyncio.gather(*tasks)) event_loop.close() http://www.baidu.com/ 200 百度一下,你就知道 https://www.v2ex.com 200 V2EX
遵从一个函数只干一件事的原则,于是我将整个 response 对象返回到列表里了,一切 ok .
就当我要把它们取出的时候 。
for i in res: i.url >https;//xx.com i.status >200 i.read() ->null 由于 response 的 read() 要使用 await 不然是获取不到的。
我尝试 :
res.append(await response) print(len(res)) --> 0
现在是没有办法了,还望表哥们给点思路
![]() | 1 ethego 2019-07-25 11:26:19 +08:00 1. `asyncio.create_task(fetch_async('http://www.baidu.com/'))` 2. 用 queue 而不是 list,并发执行是这里有竞争 |
![]() | 2 keepeye 2019-07-25 11:35:44 +08:00 遵从一个函数只干一件事的原则,于是我将整个 response 对象返回到列表里了 ----- 你为何不将 response 读出来放到 res 里呢? 好好想想如何界定"一件事" |
![]() | 你必须在 async with session.get(url) as resp:这个上下文里面 await resp.read()或者 await resp.text() 你离开这个上下文这个链接已经关闭了,你就再也不能从这个 response 里面获取数据. |
4 rainto OP @so1n 将整个 response 对象存起来,只能存到当时的状态,需要 await 的属性 就再也拿不到了嘛。 那我也有尝试过 append(await response ) 还是不可以 |