InvalidSelectorException using CSS selector to locate "data-" attribute notated elements InvalidSelectorException using CSS selector to locate "data-" attribute notated elements selenium selenium

InvalidSelectorException using CSS selector to locate "data-" attribute notated elements


The reference you linked is for Selenium IDE.

Selenium WebDriver documentation can be found mainly on the official site here (basic usage) and here (advanced usage), but also here (a.k.a "What didn't make it into the docs yet" - especially the FAQ, Advanced User Interactions and lots of info about Selenium internals). The main source of information are, of course, the JavaDocs.


Anyway. The CSS Selectors supported by Selenium are those supported by the browser beneath it (with the exception of Selenium RC which has a Sizzle CSS engine), so your example should definitely work. Using this simple testpage:

<!DOCTYPE html><html lang="en">    <head>        <meta charset="utf-8" />    </head>    <body>        <input type="text" id="myInput" class="field" data-test="testytest" />    </body></html>

I was able to sucessfully run this in both IE 8 (!!) and Firefox 13:

WebDriver driver = new FirefoxDriver();driver.get("path to the file");By cssSelector = By.cssSelector(".field[data-test='testytest']");        // or By.cssSelector(".field[data-test=testytest]")        // or By.cssSelector(".field[data-test]")driver.findElement(cssSelector).sendKeys("Hello");driver.quit();

So I digged more. If you try to run any of this in FF13 Firebug console:

document.querySelector(".field[data-test]")document.querySelector(".field[data-test=testytest]")document.querySelector(".field[data-test='testytest']")

it returns the right element. However, any of this:

document.querySelector(".field['data-test']")document.querySelector(".field[\"data-test\"]")

fails with "An invalid or illegal string was specified" error (both in Firefox and IE) which is correct (and, therefore, the error message you got was right, the selector is invalid).

Please, try once more, get rid of any quotes, make sure your type variable doesn't contain any quotes or backslashes or whatnot. The construct should definitely work. If it doesn't, post the new exception stack trace so we can see the exact selector that caused it.


I was also getting the same exception.

So I tried it by locating element through Xpath instead of Css selector and the problem was solved

Below was the Code having the problem

By.CssSelector("Css selector").GetAttribute("value");

Code which worked

By.XPath("Xpath of element").GetAttribute("value");