在 Python 中使用 Remote WebDriver 设置 Chrome DevTools (Selenium 4)

Posted

技术标签:

【中文标题】在 Python 中使用 Remote WebDriver 设置 Chrome DevTools (Selenium 4)【英文标题】:Setting up Chrome DevTools (Selenium 4) Using Remote WebDriver in Python 【发布时间】:2022-01-02 01:01:36 【问题描述】:

我一直在尝试使用 Selenium 4 和 Python 来设置 Chrome DevTools 的使用。我已经能够让它在本地运行(没有任何异步的东西),但是当我尝试使用 webdriver.Remote 实现时,它崩溃了。

这是 Selenium 文档中的一个示例:https://www.selenium.dev/de/documentation/support_packages/chrome_devtools/

以下是我尝试运行它的方式。

import asyncio

from selenium import webdriver
import selenium.webdriver.common.devtools.v96 as devtools

async def geo_location_test():
    try:
        chrome_options = webdriver.ChromeOptions()
        driver = webdriver.Remote(
            command_executor='http://D5365900:4444/wd/hub',
            options=chrome_options
        )

        async with driver.bidi_connection() as session:
            cdp_session = session.session
            await cdp_session.execute(devtools.emulation.set_geolocation_override(latitude=41.8781,
                                                                                  longitude=-87.6298,
                                                                                  accuracy=100))
        driver.get("https://my-location.org/")
    finally:
        driver.quit()


async def main():
    await geo_location_test()

if __name__ == "__main__":
    asyncio.run(main())

它运行到async with driver.bidi_connection() as session: 行(会话已建立,Chrome 浏览器打开)。但它会崩溃并出现以下跟踪。

Traceback (most recent call last):
  File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 54, in <module>
    asyncio.run(main())
  File "C:\Program Files\Python310\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Program Files\Python310\lib\asyncio\base_events.py", line 641, in run_until_complete
    return future.result()
  File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 51, in main
    await geo_location_test()
  File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 40, in geo_location_test
    async with driver.bidi_connection() as session:
  File "C:\Program Files\Python310\lib\contextlib.py", line 199, in __aenter__
    return await anext(self.gen)
  File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1576, in bidi_connection
    async with cdp.open_cdp(ws_url) as conn:
  File "C:\Program Files\Python310\lib\contextlib.py", line 199, in __aenter__
    return await anext(self.gen)
  File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\common\bidi\cdp.py", line 457, in open_cdp
    async with trio.open_nursery() as nursery:
  File "C:\Program Files\Python310\lib\site-packages\trio\_core\_run.py", line 796, in __aenter__
    self._scope.__enter__()
  File "C:\Program Files\Python310\lib\site-packages\trio\_core\_ki.py", line 159, in wrapper
    return fn(*args, **kwargs)
  File "C:\Program Files\Python310\lib\site-packages\trio\_core\_run.py", line 449, in __enter__
    task = _core.current_task()
  File "C:\Program Files\Python310\lib\site-packages\trio\_core\_run.py", line 2285, in current_task
    raise RuntimeError("must be called from async context") from None
RuntimeError: must be called from async context

如您所见,我使用的是 Python 3.10。我还将 Selenium 绑定升级到 4.1.0,并运行 Selenium 4.0.0 Hub/Node 配置来自动化 Chrome 96。

任何想法,这里有什么问题?我是否错误地处理了异步协程?

非常感谢任何帮助!

更新 在尝试使用 trio 运行它之后(如 Henry Ashton-Martyn 的评论中所建议的那样),我收到以下错误。

Traceback (most recent call last):
  File "C:\Program Files\Python310\lib\site-packages\trio\_highlevel_open_tcp_stream.py", line 332, in attempt_connect
    await sock.connect(sockaddr)
  File "C:\Program Files\Python310\lib\site-packages\trio\_socket.py", line 682, in connect
    raise OSError(err, "Error in connect: " + os.strerror(err))
OSError: [Errno 10049] Error in connect: Unknown error

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 58, in <module>
    trio.run(main)
  File "C:\Program Files\Python310\lib\site-packages\trio\_core\_run.py", line 1932, in run
    raise runner.main_task_outcome.error
  File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 55, in main
    await geo_location_test()
  File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 44, in geo_location_test
    async with driver.bidi_connection() as session:
  File "C:\Program Files\Python310\lib\contextlib.py", line 199, in __aenter__
    return await anext(self.gen)
  File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1576, in bidi_connection
    async with cdp.open_cdp(ws_url) as conn:
  File "C:\Program Files\Python310\lib\contextlib.py", line 199, in __aenter__
    return await anext(self.gen)
  File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\common\bidi\cdp.py", line 458, in open_cdp
    conn = await connect_cdp(nursery, url)
  File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\common\bidi\cdp.py", line 479, in connect_cdp
    ws = await connect_websocket_url(nursery, url,
  File "C:\Program Files\Python310\lib\site-packages\trio_websocket\_impl.py", line 262, in connect_websocket_url
    return await connect_websocket(nursery, host, port, resource,
  File "C:\Program Files\Python310\lib\site-packages\trio_websocket\_impl.py", line 171, in connect_websocket
    stream = await trio.open_tcp_stream(host, port)
  File "C:\Program Files\Python310\lib\site-packages\trio\_highlevel_open_tcp_stream.py", line 367, in open_tcp_stream
    raise OSError(msg) from trio.MultiError(oserrors)
OSError: all attempts to connect to 0.0.0.0:4444 failed

【问题讨论】:

【参考方案1】:

selenium 似乎没有使用 python 的内置异步框架,而是使用a package called trio as well。您应该可以通过更改以下代码来解决此问题:

if __name__ == "__main__":
    asyncio.run(main())

到:

if __name__ == "__main__":
    import trio
    trio.run(main)

【讨论】:

感谢您的建议。我之前确实尝试过。当我尝试使用 trio 时,我更新了我的帖子以显示我得到的(不同的)错误。

以上是关于在 Python 中使用 Remote WebDriver 设置 Chrome DevTools (Selenium 4)的主要内容,如果未能解决你的问题,请参考以下文章

Python教程:selenium模块用法教程

VS code 使用 Remote-SSH 进行python远程开发

VS code 使用 Remote-SSH 进行python远程开发

VS code 使用 Remote-SSH 进行python远程开发

python selenium都在一个会话浏览器中进行测试

Python发邮件