InvalidArgumentException
InvalidArgumentException: Causes and Fixes
Fix Selenium InvalidArgumentException (InvalidArgumentError in JS): URLs without a scheme, missing upload files, bad capabilities and invalid cookie fields.
| Java | org.openqa.selenium.InvalidArgumentException |
|---|---|
| Python | selenium.common.exceptions.InvalidArgumentException |
| JavaScript | InvalidArgumentError |
| C# | OpenQA.Selenium.WebDriverArgumentException |
What the error means
The driver received a command whose parameters it considers invalid: the right command, the wrong value. It is the WebDriver equivalent of a 400 Bad Request. The browser never tried to perform the action because the input failed validation first.
Because the problem is in what you sent, the fix is always in your code or configuration, and it reproduces on every run. The message usually names the offending value, so read it closely.
What it looks like
// Java: navigating without a schemeorg.openqa.selenium.InvalidArgumentException: invalid argument (Session info: chrome=131.0.6778.86) at org.openqa.selenium.remote.RemoteWebDriver.get(RemoteWebDriver.java:...)# Python: file upload path does not exist on the browser's machineselenium.common.exceptions.InvalidArgumentException: Message: invalid argument: File not found : /home/ci/fixtures/invoice.pdf (Session info: chrome=131.0.6778.86)// JavaScript (selenium-webdriver): misspelt Chrome optionInvalidArgumentError: invalid argument: cannot parse capability: goog:chromeOptionsfrom invalid argument: unrecognized chrome option: excludeSwitchess// C#OpenQA.Selenium.WebDriverArgumentException : invalid argument: invalid 'expiry'Common causes
- A URL without a scheme.
driver.get("example.com")or a relative path; WebDriver requires an absolute URL such ashttps://example.com. - A file upload path that does not exist where the browser runs. A relative path, a typo, or a local file sent to a remote Grid node without file detection.
- Invalid capabilities or browser options. Misspelt option names, wrong value types, or vendor options in the wrong place.
- Invalid cookie fields. An
expiryin milliseconds instead of seconds, an unsupportedsameSitevalue, or missing name or value. - An unsupported locator for the search context. XPath against a shadow root in Chromium-based browsers.
- Bad parameters to window or action commands. Negative or non-integer window sizes, or malformed action sequences built by hand.
How to fix it
A URL without a scheme
Always build absolute URLs. A small helper that joins a base URL from configuration with a path removes the problem everywhere.
String baseUrl = System.getenv().getOrDefault("BASE_URL", "https://staging.example.com");driver.get(URI.create(baseUrl).resolve("/login").toString());import osfrom urllib.parse import urljoin
base_url = os.environ.get("BASE_URL", "https://staging.example.com")driver.get(urljoin(base_url, "/login"))const baseUrl = process.env.BASE_URL || 'https://staging.example.com';await driver.get(new URL('/login', baseUrl).toString());var baseUrl = new Uri(Environment.GetEnvironmentVariable("BASE_URL") ?? "https://staging.example.com");driver.Navigate().GoToUrl(new Uri(baseUrl, "/login"));A file upload path that does not exist
sendKeys on a file input needs an absolute path to a file on the machine where the browser runs. Resolve fixture paths to absolute paths, and when running on a Grid, enable file detection so the client uploads the file to the node first.
Path file = Paths.get("src/test/resources/invoice.pdf").toAbsolutePath();
if (driver instanceof RemoteWebDriver remote) { remote.setFileDetector(new LocalFileDetector());}driver.findElement(By.cssSelector("input[type='file']")).sendKeys(file.toString());from pathlib import Path
file = Path("tests/fixtures/invoice.pdf").resolve()# webdriver.Remote uses a LocalFileDetector by default, so the file is uploaded to the nodedriver.find_element(By.CSS_SELECTOR, "input[type='file']").send_keys(str(file))const path = require('node:path');const remote = require('selenium-webdriver/remote');
const file = path.resolve('test/fixtures/invoice.pdf');driver.setFileDetector(new remote.FileDetector());await driver.findElement(By.css("input[type='file']")).sendKeys(file);string file = Path.GetFullPath("Fixtures/invoice.pdf");
if (driver is IAllowsFileDetection detecting){ detecting.FileDetector = new LocalFileDetector();}driver.FindElement(By.CssSelector("input[type='file']")).SendKeys(file);For multiple files, join absolute paths with a newline character. The remote upload recipe and the file uploads lesson cover the details.
Invalid capabilities or browser options
Use the typed Options classes and their methods rather than hand-built capability maps; they catch most mistakes at compile time or construction. When the driver rejects an option, the message names it (unrecognized chrome option: ...). Common mistakes:
- Putting Chrome arguments at the top level instead of inside
goog:chromeOptions, which the Options classes handle for you. - Passing a string where a list or boolean is expected in
setExperimentalOption/add_experimental_option. - Using
DesiredCapabilitiescopied from Selenium 3 examples. Replace them withChromeOptions,FirefoxOptions,EdgeOptionsorSafariOptions.
Older ChromeDriver versions also reported a locked profile (user data directory is already in use) as an invalid argument; current versions report it as SessionNotCreatedException, which covers the fix.
Invalid cookie fields
Cookie expiry is seconds since the Unix epoch, not milliseconds. sameSite accepts Strict, Lax or None (and None requires secure). Navigate to the cookie’s domain before adding it.
driver.get("https://staging.example.com/");Cookie consent = new Cookie.Builder("consent", "accepted") .domain("staging.example.com") .path("/") .expiresOn(Date.from(Instant.now().plus(Duration.ofDays(30)))) .sameSite("Lax") .build();driver.manage().addCookie(consent);import time
driver.get("https://staging.example.com/")driver.add_cookie({ "name": "consent", "value": "accepted", "path": "/", "expiry": int(time.time()) + 30 * 24 * 3600, # seconds, not ms "sameSite": "Lax",})await driver.get('https://staging.example.com/');await driver.manage().addCookie({name: 'consent',value: 'accepted',path: '/',expiry: new Date(Date.now() + 30 * 24 * 3600 * 1000),sameSite: 'Lax',});driver.Navigate().GoToUrl("https://staging.example.com/");var consent = new Cookie("consent", "accepted", "staging.example.com", "/", DateTime.UtcNow.AddDays(30), false, false, "Lax");driver.Manage().Cookies.AddCookie(consent);Adding a cookie for a domain you are not currently on gives a related but distinct error, InvalidCookieDomainException. See cookies and storage.
An unsupported locator for the search context
Shadow roots in Chromium-based browsers only support CSS selectors. Using XPath (or By.tagName in some versions) against a shadow root can return invalid argument: invalid locator. Switch to CSS for anything inside the shadow root.
Bad parameters to window or action commands
Window sizes and positions must be non-negative integers. If you compute them (for example from a device profile), validate first. Prefer the Actions API builder methods to hand-built action JSON.
How to prevent it
- Centralise URL building around a configured absolute base URL.
- Resolve every fixture path to an absolute path, and configure file detection once in your remote driver factory.
- Use typed Options classes exclusively; log the final capabilities at session start.
- Wrap cookie creation in a helper that enforces seconds-based expiry and valid
sameSitevalues. - Use CSS selectors inside shadow roots.
Related errors
- SessionNotCreatedException: invalid options sometimes surface while creating the session.
- InvalidSelectorException: the locator is valid for the context but malformed.
- ElementNotInteractableException: the file input exists but the browser will not accept input for it.
- NoSuchShadowRootException: another shadow DOM error, for hosts without a shadow root.
Go deeper
- File Uploads Handle file uploads in Selenium tests by interacting with file input elements.
- Browser Options & Configuration Learn how to configure browser options in Selenium WebDriver, including headless mode, window size, and custom arguments.
- Cookies, Local Storage and Session Storage Read, add and delete cookies, reuse a login session across tests, inspect localStorage and sessionStorage, and understand the domain and secure-flag rules that make cookie injection fail.
- Navigation and Browser Control Open URLs, move back and forward, refresh, read the title and URL, manage window size and position, maximise, full-screen, and close cleanly.