【问题标题】:Creating multiple async requests创建多个异步请求
【发布时间】: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


    【解决方案1】:

    我已经知道怎么做了。

    创建列表后,我们必须调用

    asession.run(*tasks)
    

    这样,我们确保我们只将可调用对象传递给 run 方法,即列表的元素而不是列表本身。

    由!

    【讨论】:

      猜你喜欢
      • 2015-01-17
      • 1970-01-01
      • 2012-05-26
      • 2018-04-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2019-01-05
      • 2011-01-08
      相关资源
      最近更新 更多