Motivation
To utilize Selenium's CSS selector mechanism alongside with CSS attribute selectors and the HTML5 data- custom attribute to address specific hooks for elements.
Issue
While using the above to locate an element assigned with a CSS classname and the data- attribute, the following exception is thrown:
Caused by: org.openqa.selenium.remote.ErrorHandler$UnknownServerException: The given selector .gs-a-btn["data-value"] is either invalid or does not result in a WebElement. The following error occurred:
[Exception... "An invalid or illegal string was specified" code: "12" nsresult: "0x8053000c (NS_ERROR_DOM_SYNTAX_ERR)" location: "file:///C:/DOCUME~1/eliranm/LOCALS~1/Temp/anonymous6109849275533680625webdriver-profile/extensions/[email protected]/components/driver_component.js Line: 5956"]
Build info: version: '2.23.1', revision: '17143', time: '2012-06-08 18:59:28'
System info: os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.6.0_31'
Driver info: driver.version: unknown
at <anonymous class>.<anonymous method>(file:///C:/DOCUME~1/eliranm/LOCALS~1/Temp/anonymous6109849275533680625webdriver-profile/extensions/[email protected]/components/driver_component.js:6537)
Relevant Code
public void previous(String type) {
By cssSelector = By.cssSelector(".gs-a-btn[data-value='" + type + "']");
driver.findElement(cssSelector).click();
}
What have I tried
- replacing single quotes with escaped double quotes inside the attribute selector query.
- specifying attribute selector instead of attribute-value selector, i.e.
".gs-a-btn[\"data-value\"]"rather".gs-a-btn[data-value='" + type + "']". to look up information in references, such as the Selenium Reference, for any restrictions on CSS attribute selectors. the document specifically states that:
Currently the css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(
:nth-of-type,:nth-last-of-type,:first-of-type,:last-of-type,:only-of-type,:visited,:hover,:active,:focus,:indeterminate) and pseudo elements(::first-line,::first-letter,::selection,::before,::after).
typevalue?By.cssSelectorwith attribute selectors seem slower than merely usingBy.className. it is failing sporadically.By.classNameinternally uses (at least on Firefox)document.getElementsByClassName()(which is cached) and should, therefore, be almost instant.By.cssSelectorusesdocument.querySelector()anddocument.querySelectorAll()which takes a while to parse and process. If it's a timing issue, I'd expect an occasionalNoSuchElementException(which can be fixed), not a strangeUnknownServerException.