NEWStandard createTask and in.php APIs. Change the address and you are connected.View API docs
GATESOLVER

Web scraping

How to change the user agent in Selenium

Selenium lets you replace the browser's user agent in two ways: a launch argument and a DevTools override. The second one also controls client hints, which is what keeps the new identity consistent.

What changing the user agent actually changes

The user agent string appears in two places: the User-Agent request header and navigator.userAgent in JavaScript. Modern Chromium also publishes the same identity in a structured form, through Sec-CH-UA request headers and the navigator.userAgentData object. A site that reads both and finds a Windows Chrome string next to Linux client hints sees a contradiction, and contradictions are what bot scoring looks for.

So the goal is not merely a different string. The goal is one coherent browser description: header, JavaScript property, client hints and navigator.platform all agreeing. Selenium can get you there with Chrome, and partly with Firefox, as shown below.

Set it with a Chrome launch argument

The quickest method is the --user-agent switch. It changes the header and navigator.userAgent for every tab the driver opens, and it needs no extra API calls.

import selenium.webdriver as sw

DESKTOP_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
              "AppleWebKit/537.36 (KHTML, like Gecko) "
              "Chrome/131.0.0.0 Safari/537.36")

chrome_opts = sw.ChromeOptions()
chrome_opts.add_argument("--headless=new")
chrome_opts.add_argument(f"--user-agent={DESKTOP_UA}")
driver = sw.Chrome(options=chrome_opts)
driver.get("https://example.com/")
print(driver.execute_script("return navigator.userAgent"))

Selenium 4 downloads a matching driver through Selenium Manager, so this runs without a separate chromedriver install. The version in the example string is only a placeholder: copy the major version of the Chrome you actually launch, which driver.capabilities["browserVersion"] reports. A string that claims a newer or much older release than the engine behind it is easy to spot, because feature checks in JavaScript reveal the real engine.

The limit of the launch argument

The switch leaves client hints alone. navigator.userAgentData.platform still reports the real operating system, and the Sec-CH-UA-Platform header follows it. If your scraper runs on a Linux server and the string says Windows, those values disagree. For simple sites that read only the header this does not matter; for sites with active browser fingerprinting it does.

Override it through the DevTools protocol

Chrome's DevTools protocol has a command that sets the string, the platform and the full client hint metadata together. Selenium's Chrome driver exposes it as execute_cdp_cmd. Call it before the first navigation so no request leaves with the old identity.

def apply_identity(drv, ua, major):
    hints = {
        "brands": [{"brand": "Google Chrome", "version": major},
                   {"brand": "Chromium", "version": major},
                   {"brand": "Not_A Brand", "version": "24"}],
        "platform": "Windows", "platformVersion": "15.0.0",
        "architecture": "x86", "bitness": "64",
        "model": "", "mobile": False,
    }
    drv.execute_cdp_cmd("Network.setUserAgentOverride", {
        "userAgent": ua, "platform": "Win32",
        "acceptLanguage": "en-US,en;q=0.9",
        "userAgentMetadata": hints,
    })

apply_identity(driver, DESKTOP_UA, "131")
driver.get("https://example.com/")

The platform argument sets navigator.platform, and userAgentMetadata fills the client hints. The brand list, including the deliberately odd "Not A Brand" entry, mirrors what real Chrome sends; check the current values in a normal Chrome window, since Google changes the filler brand from time to time. The field names follow the protocol documentation at the time of writing, so confirm them against the current DevTools protocol reference if the command starts returning errors.

Scope of the override

The override applies to the target it was sent to. New tabs or windows opened later may start with the default identity, so call the helper again after switching to a new window handle. Pages that spawn service workers can also send requests outside the overridden target; if that matters, set the launch argument as well so both paths agree.

Firefox through a preference

Firefox has no DevTools override, but it reads a preference at startup:

fox_opts = sw.FirefoxOptions()
fox_opts.set_preference("general.useragent.override", DESKTOP_UA.replace(
    "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    "Gecko/20100101 Firefox/133.0"))
fox = sw.Firefox(options=fox_opts)

Give Firefox a Firefox string. Presenting a Chrome identity from the Gecko engine is the kind of mismatch that undoes the whole exercise, because Firefox does not send Chromium client hints at all.

Verify what the site receives

Never assume the change worked; read it back. In the page, check navigator.userAgent, navigator.platform and the result of navigator.userAgentData.getHighEntropyValues(["platform", "platformVersion", "fullVersionList"]). For headers, load a page you control that echoes request headers, or log them on a local test server. Make the check part of your test suite so an upgrade of Chrome or Selenium that changes behavior is caught on the first run.

Also remember that the user agent is one signal among many. navigator.webdriver, the TLS handshake and the screen size all describe the browser too. Changing the string to match a laptop while the window reports an 800 by 600 screen produces another mismatched user agent pattern.

Keep the identity consistent with CAPTCHA tokens

Token answers come with the browser identity they were produced under. A reCAPTCHA v2 task returns userAgent next to gRecaptchaResponse, and a Cloudflare Challenge task accepts a userAgent field and returns the cf_clearance cookie that is valid only for that string and the proxy IP you supplied. When a Selenium session will submit the token or reuse the cookie, set the driver's user agent to that same value before you continue, ideally with the CDP helper above so the hints agree as well.

A practical order for the Cloudflare case: choose the user agent first, launch Selenium with it, send the same string in the task's userAgent field together with the proxy the browser uses, then add the returned cookie with driver.add_cookie and reload. Our guide on reusing cf_clearance explains why the IP and string have to stay fixed for the life of the cookie.

Choosing which string to use

Use a current, common desktop string that matches the engine you actually run, and keep it stable for the length of a session. Rotating on every request is counterproductive; a real visitor's browser does not change identity between page views. The article on picking user agents for scrapers goes deeper into building a small, maintained pool.

Common questions

Does the --user-agent switch work in headless mode?

Yes. It also removes the HeadlessChrome token from the string, which the default headless user agent includes.

Can I change the user agent after the page has loaded?

With the CDP command you can, but only later requests and newly loaded pages use the new value, so set it before navigating whenever possible.

Is execute_cdp_cmd available for Edge?

Edge is Chromium based and its Selenium driver exposes the same method, so the override works there with Edge brand names in the metadata.

Why do client hints matter if the header is correct?

Many detection scripts read navigator.userAgentData and the Sec-CH-UA headers and compare them with the classic string. Disagreement raises suspicion.

Should I copy the userAgent from a solved token into my browser?

When you submit that token from Selenium, yes. Matching the identity the answer was produced under removes one reason for a site to reject it.

Keep reading