【问题标题】:How to change at runtime the user-agent of a Remote Selenium Driver?如何在运行时更改远程 Selenium 驱动程序的用户代理?
【发布时间】:2021-04-13 15:16:30
【问题描述】:

根据标题,我有一个远程 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)

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

我还找到了 this thread 以及 execute_cdp_cmd 函数,但它仅适用于 Chrome,不适用于 Remote。

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

提前谢谢你

【问题讨论】:

标签: python selenium google-chrome selenium-webdriver


【解决方案1】:

找到了方法。与其将 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没有这个功能,会导致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;")

【讨论】:

    猜你喜欢
    • 2020-04-22
    • 2015-07-07
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 2019-07-21
    • 2021-09-20
    相关资源
    最近更新 更多