【发布时间】:2020-01-14 22:51:25
【问题描述】:
我刚刚开始探索这个名为Requests-Html 的新库,我刚刚通过Corey Schafer tutorial 发现了它,挑战是创建n 个不同请求的异步调用。
因此,例如,我们有以下代码,运行时间约为 3.6 秒:
async def get_delay1():
r = await asession.get("https://httpbin.org/delay/1")
return r
async def get_delay2():
r = await asession.get("https://httpbin.org/delay/2")
return r
async def get_delay3():
r = await asession.get("https://httpbin.org/delay/3")
return r
asession = AsyncHTMLSession()
t1 = time.perf_counter()
results = asession.run(get_delay1, get_delay2, get_delay3)
for result in results:
response = result.html.url
print(response)
t2 = time.perf_counter()
print(t2 - t1)
问题是,如果我想用这个库创建一个 500 的异步请求该怎么办?不可能我必须编写 500 个不同的函数,对吧?
我尝试使用函数生成器创建一个列表,以便我可以在其中自动传递 n 个不同的函数:
tasks = [get_delay1, get_delay2, get_delay3]
results = asession.run(tasks)
但我明白了
ERROR`:
asyncio.ensure_future(coro()) for coro in coros
TypeError: 'list' object is not callable
【问题讨论】:
标签: python web-scraping python-asyncio python-requests-html