Python 如何在运行时更改远程Selenium驱动程序的用户代理?

Python 如何在运行时更改远程Selenium驱动程序的用户代理?,python,selenium,google-chrome,selenium-webdriver,Python,Selenium,Google Chrome,Selenium Webdriver,根据标题,我有一个远程selenium驱动程序(具有Chrome功能),我需要在不创建其他驱动程序的情况下更改其用户代理。 我的远程驱动程序设置如下: 从selenium.webdriver导入Chrome,远程 从selenium.webdriver.chrome.options导入选项 从selenium.webdriver.common.desired_功能导入DesiredCapabilities url=”http://selenium-hub:4444/wd/hub" 驱动程序=远程

根据标题,我有一个远程selenium驱动程序(具有Chrome功能),我需要在不创建其他驱动程序的情况下更改其用户代理。

我的远程驱动程序设置如下:

从selenium.webdriver导入Chrome,远程
从selenium.webdriver.chrome.options导入选项
从selenium.webdriver.common.desired_功能导入DesiredCapabilities
url=”http://selenium-hub:4444/wd/hub"
驱动程序=远程(url,所需的功能=DesiredCapabilities.CHROME)
我已经知道,标准方法是创建Chrome选项,并添加如下用户代理参数:

options=options()
options.add_参数(f“user agent={my_user_agent}”)
驱动程序=镀铬(选项=选项)
#也为远程计算机工作
#驱动程序=远程(url,所需功能=DesiredCapabilities.CHROME,选项=选项)
但是,如前所述,我需要在同一个驱动程序中更改用户代理,而无需创建另一个

我还发现了它的功能,但它只适用于Chrome,不适用于Remote

有没有办法在远程驱动程序上运行此指令?还是另一种“动态”设置用户代理的方法


提前谢谢你找到了一条路。不要将Selenium hub的url作为第一个参数(
command\u executor
)提供,您需要将其包装在ChromeRemoteConnection中,如下所示:

从selenium.webdriver.chrome.remote\u连接导入ChromeRemoteConnection
驱动程序=远程(
ChromeRemoteConnection(远程服务器地址=url),
所需的功能=所需的功能.CHROME
)
在此之后,用户代理可以进行动态更改;但是,不需要调用
execute\u cdp\u cmd
(Remote没有此功能,导致AttributeError),代码的内行可以安全地执行

cmd=“Network.setUserAgentOverride”
ua=“我的全新用户代理!”
cmd_args=dict(userAgent=ua)
execute(“executeCdpCommand”,{“cmd”:cmd,“params”:cmd_args})
assert ua==driver.execute_脚本(“return navigator.userAgent;”)

这是否回答了您的问题?很遗憾,答案是否定的,因为接受的答案是在创建驱动程序之前设置用户代理