繁体   English   中英

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

[英]How to change at runtime the user-agent of a Remote Selenium Driver?

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

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

from selenium.webdriver import Chrome, Remote
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities


url = "http://selenium-hub:4444/wd/hub"
driver = Remote(url, desired_capabilities=DesiredCapabilities.CHROME)

我已经知道标准方法是创建 Chrome 选项,并添加这样的用户代理参数:

options = Options()
options.add_argument(f"user-agent={my_user_agent}")
driver = Chrome(options=options)
# also working for remote
# driver = Remote(url, desired_capabilities=DesiredCapabilities.CHROME, options=options)

但是,如前所述,我需要在同一个驱动程序中更改用户代理而不创建另一个。

我还找到了这个线程,并从中找到了 function execute_cdp_cmd ,但它仅适用于 Chrome,不适用于 Remote。

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

先感谢您

找到了办法。 与其将 Selenium 集线器的 url 作为第一个参数 ( command_executor ),不如将其包装在 ChromeRemoteConnection 中,如下所示:

from selenium.webdriver.chrome.remote_connection import ChromeRemoteConnection

driver = Remote(
    ChromeRemoteConnection(remote_server_addr=url),
    desired_capabilities=DesiredCapabilities.CHROME
)

在此之后,用户代理可以动态更改; 但是,与其调用execute_cdp_cmd (Remote没有这个function,导致AttributeError),而是可以安全地执行内部代码行。

cmd = "Network.setUserAgentOverride"
ua = "My brand new user agent!"
cmd_args = dict(userAgent=ua)

driver.execute("executeCdpCommand", {"cmd": cmd, "params": cmd_args})
assert ua == driver.execute_script("return navigator.userAgent;")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM