0

As per title, I have a Remote selenium driver (with Chrome capabilities), and I need to change its user agent without creating another driver.

My remote driver is set like this:

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)

I know already that the standard way is to create Chrome Options, and add user-agent argument like this:

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)

But, as said before, I need to change the user-agent within the same driver without creating another one.

I also found this thread and, from it, the function execute_cdp_cmd, but it's only working for Chrome, not for Remote.

Is there a way to run this instruction on a Remote driver? Or another way to set a user-agent "dynamically"?

Thank you in advance

crissal
  • 2,547
  • 7
  • 25
  • Does this answer your question? https://stackoverflow.com/questions/29916054/change-user-agent-for-selenium-web-driver – Dan Mullin Apr 13 '21 at 17:32
  • Unfortunately no, because the accepted answer refers to setting user agent **before** creating the driver – crissal Apr 13 '21 at 17:39

1 Answers1

0

Found a way. Instead of giving as first argument (command_executor) just the url of the Selenium hub, you need to wrap it inside a ChromeRemoteConnection like this:

from selenium.webdriver.chrome.remote_connection import ChromeRemoteConnection

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

After this, the user-agent can be changed dinamically; however, instead of calling execute_cdp_cmd (Remote doesn't have this function, resulting in an AttributeError), the inner line of code can be executed safely.

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;")
crissal
  • 2,547
  • 7
  • 25