InvalidSelectorException
InvalidSelectorException: Causes and Fixes
Fix Selenium InvalidSelectorException (InvalidSelectorError in JS): XPath and CSS syntax errors, XPath 2.0 functions, text() results and jQuery pseudo-classes.
| Java | org.openqa.selenium.InvalidSelectorException |
|---|---|
| Python | selenium.common.exceptions.InvalidSelectorException |
| JavaScript | InvalidSelectorError |
| C# | OpenQA.Selenium.InvalidSelectorException |
What the error means
The browser could not even evaluate your locator. Unlike NoSuchElementException, which means “valid query, zero matches”, this error means the query itself is broken: a syntax error, a function the browser does not support, or an XPath that returns something other than elements.
The good news: it is deterministic. The same locator fails every time, on every run, so once you find the mistake it is fixed for good.
What it looks like
// Java: broken XPathorg.openqa.selenium.InvalidSelectorException: invalid selector: Unable to locate an element with the xpath expression //button[@class='save' because of the following error:SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//button[@class='save'' is not a valid XPath expression. (Session info: chrome=131.0.6778.86)# Python: XPath returning a text nodeselenium.common.exceptions.InvalidSelectorException: Message: invalid selector: The result of the xpath expression "//td[@class='price']/text()" is: [object Text]. It should be an element.// JavaScript (selenium-webdriver): broken CSSInvalidSelectorError: invalid selector: An invalid or illegal selector was specified (Session info: chrome=131.0.6778.86)// C#OpenQA.Selenium.InvalidSelectorException : invalid selector: An invalid or illegal selector was specifiedFirefox reports CSS problems as Given css selector expression "div:contains('Save')" is invalid: SyntaxError: ... and XPath problems with Given xpath expression ... is invalid.
In Java, InvalidSelectorException is a subclass of NoSuchElementException, so a broad catch (NoSuchElementException e) will also swallow it. Watch out for that when a “missing element” never seems to appear.
Common causes
- Syntax errors. Unbalanced brackets or quotes, a missing
@,=where==was not needed, a trailing slash. - XPath that returns non-elements.
/text(),/@href,count(...)orstring(...)return text, attributes or numbers;findElementneeds element nodes. - XPath 2.0 or 3.0 functions. Browsers implement XPath 1.0 only, so
matches(),lower-case(),ends-with()andstring-join()fail. - jQuery or Sizzle pseudo-classes in CSS.
:contains(),:eq(),:first,:visibleare not standard CSS. - Quotes in dynamically built locators. Interpolating text like
O'Brieninto//td[text()='...']breaks the expression. - Unsupported strategies in a shadow root. Searching a shadow root with XPath is not supported in Chromium-based browsers.
How to fix it
Syntax errors
Paste the exact locator into the DevTools Elements search (Ctrl+F). For XPath you can also run $x("//button[@class='save']") in the console, and for CSS document.querySelectorAll("..."). The console gives a precise syntax error.
XPath that returns non-elements
Locate the element, then read the text or attribute through the WebDriver API.
// Wrong: By.xpath("//td[@class='price']/text()")String price = driver.findElement(By.xpath("//td[@class='price']")).getText();
// Wrong: By.xpath("//a[@id='docs']/@href")String href = driver.findElement(By.id("docs")).getDomAttribute("href");# Wrong: (By.XPATH, "//td[@class='price']/text()")price = driver.find_element(By.XPATH, "//td[@class='price']").text
# Wrong: (By.XPATH, "//a[@id='docs']/@href")href = driver.find_element(By.ID, "docs").get_dom_attribute("href")// Wrong: By.xpath("//td[@class='price']/text()")const price = await driver.findElement(By.xpath("//td[@class='price']")).getText();
// Wrong: By.xpath("//a[@id='docs']/@href")const href = await driver.findElement(By.id('docs')).getDomAttribute('href');// Wrong: By.XPath("//td[@class='price']/text()")string price = driver.FindElement(By.XPath("//td[@class='price']")).Text;
// Wrong: By.XPath("//a[@id='docs']/@href")string href = driver.FindElement(By.Id("docs")).GetDomAttribute("href");Text predicates are fine: //td[text()='9.99'] returns the td element, which is valid. It is only a trailing /text() step that returns a text node.
XPath 2.0 functions
Rewrite with XPath 1.0 equivalents.
| XPath 2.0 (fails) | XPath 1.0 equivalent |
|---|---|
ends-with(@id, '-save') | substring(@id, string-length(@id) - 4) = '-save' |
lower-case(text()) = 'save' | translate(text(), 'SAVE', 'save') = 'save' |
matches(@id, '^btn-[0-9]+$') | starts-with(@id, 'btn-') (and check the rest in code) |
Often CSS is simpler: [id$='-save'] does ends-with natively.
jQuery or Sizzle pseudo-classes in CSS
Standard CSS cannot match on text. Use XPath for text, or a CSS attribute selector when there is a usable attribute.
// Wrong: By.cssSelector("button:contains('Save')")By save = By.xpath("//button[normalize-space()='Save']");
// Wrong: By.cssSelector("tr:eq(2)") (zero-based in jQuery)By thirdRow = By.cssSelector("tbody tr:nth-child(3)");# Wrong: (By.CSS_SELECTOR, "button:contains('Save')")save = (By.XPATH, "//button[normalize-space()='Save']")
# Wrong: (By.CSS_SELECTOR, "tr:eq(2)")third_row = (By.CSS_SELECTOR, "tbody tr:nth-child(3)")// Wrong: By.css("button:contains('Save')")const save = By.xpath("//button[normalize-space()='Save']");
// Wrong: By.css('tr:eq(2)')const thirdRow = By.css('tbody tr:nth-child(3)');// Wrong: By.CssSelector("button:contains('Save')")By save = By.XPath("//button[normalize-space()='Save']");
// Wrong: By.CssSelector("tr:eq(2)")By thirdRow = By.CssSelector("tbody tr:nth-child(3)");Quotes in dynamically built locators
XPath 1.0 has no escape character. If the text may contain a single quote, wrap it in double quotes; if it may contain both, use concat(). Better: avoid building locators from data at all and filter elements in code.
static String xpathLiteral(String s) { if (!s.contains("'")) return "'" + s + "'"; if (!s.contains("\"")) return "\"" + s + "\""; return "concat('" + s.replace("'", "', \"'\", '") + "')";}
By row = By.xpath("//td[normalize-space()=" + xpathLiteral("O'Brien") + "]");def xpath_literal(s: str) -> str: if "'" not in s: return f"'{s}'" if '"' not in s: return f'"{s}"' return "concat('" + s.replace("'", "', \"'\", '") + "')"
name = xpath_literal("O'Brien")row = (By.XPATH, f"//td[normalize-space()={name}]")function xpathLiteral(s) {if (!s.includes("'")) return "'" + s + "'";if (!s.includes('"')) return '"' + s + '"';return "concat('" + s.split("'").join("', \"'\", '") + "')";}
const row = By.xpath('//td[normalize-space()=' + xpathLiteral("O'Brien") + ']');static string XPathLiteral(string s){ if (!s.Contains('\'')) return "'" + s + "'"; if (!s.Contains('"')) return "\"" + s + "\""; return "concat('" + s.Replace("'", "', \"'\", '") + "')";}
By row = By.XPath("//td[normalize-space()=" + XPathLiteral("O'Brien") + "]");Unsupported strategies in a shadow root
Inside a shadow root, use CSS selectors only. If you need text matching, find candidates with CSS and filter by getText() in code. See the shadow DOM lesson.
How to prevent it
- Validate every new locator in DevTools before committing it.
- Default to CSS; reach for XPath only for text matching or ancestor navigation, and keep it XPath 1.0.
- Never copy jQuery selectors from application code into tests without checking they are standard CSS.
- Avoid string-built XPath with user data; if unavoidable, use a literal helper like the one above.
- Add a quick smoke test that runs each page object’s locators once, so a typo fails fast rather than deep in a long flow.
Related errors
- NoSuchElementException: the locator is valid but matches nothing.
- InvalidArgumentException: some drivers report unsupported locator strategies, especially in shadow roots, this way.
- NoSuchShadowRootException: the element you tried to search inside has no shadow root.
- JavascriptException: a selector passed to
querySelectorin your own script failed.
Go deeper
- XPath Basics Learn XPath fundamentals for locating elements when CSS selectors aren't enough.
- XPath Advanced Techniques Master advanced XPath patterns for complex element location scenarios.
- CSS Selectors Master CSS selectors for finding elements in Selenium. Learn syntax, best practices, and common patterns.
- Locator Strategy Guide A decision framework for choosing locators that survive UI changes: test IDs, the priority order, handling dynamic attributes, text-based lookups, uniqueness checks, and the anti-patterns that make suites brittle.