作为标题,我有一个远程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,而不是远程的。
有办法在远程驱动程序上运行此指令吗?或者另一种“动态”设置用户代理的方法?
提前谢谢你
发布于 2021-04-20 13:03:17
找到办法了。与其仅给出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;")https://stackoverflow.com/questions/67077671
复制相似问题