【问题标题】:python - webdriver and asynciopython - webdriver 和 asyncio
【发布时间】:2018-10-22 13:09:33
【问题描述】:

是否可以先为每个任务打开浏览器,然后再加载链接? 此代码引发错误

import asyncio
from selenium import webdriver

async def get_html(url):
    driver = await webdriver.Chrome()
    response = await driver.get(url)

TypeError: object WebDriver can't be used in 'await' expression

【问题讨论】:

    标签: python selenium asynchronous webdriver python-asyncio


    【解决方案1】:

    如果您想以异步方式使用 Selenium,我建议您使用多个驱动程序实例和一个执行器,如下所示:

    import asyncio
    from concurrent.futures.thread import ThreadPoolExecutor
    
    from selenium import webdriver
    
    executor = ThreadPoolExecutor(10)
    
    
    def scrape(url, *, loop):
        loop.run_in_executor(executor, scraper, url)
    
    
    def scraper(url):
        driver = webdriver.Chrome("./chromedriver")
        driver.get(url)
    
    
    loop = asyncio.get_event_loop()
    for url in ["https://google.de"] * 2:
        scrape(url, loop=loop)
    
    loop.run_until_complete(asyncio.gather(*asyncio.all_tasks(loop)))
    

    请注意,您可以在无头模式下运行 selenium,因此您无需生成整个 GUI 来调用一些简单的 url。

    【讨论】:

      【解决方案2】:

      这个问题在https://github.com/SeleniumHQ/selenium/issues/3399讨论过

      如果您想拥有异步网络驱动程序,可以使用两个库:

      【讨论】:

        猜你喜欢
        • 2014-01-10
        • 2018-05-04
        • 1970-01-01
        • 1970-01-01
        • 2018-02-10
        • 1970-01-01
        • 1970-01-01
        • 2021-04-13
        • 2022-01-16
        相关资源
        最近更新 更多