TLDR: Selecting an id with a fullstop or period in it requires a little escaping with CSS selectors. \.
Context
I was working with a site and trying to select an element via its id
e.g.
<button id="select.me.by.id">Select Me By id</p>
This is not as simple as:
#select.me.by.id
Try with XPath, and that works fine:
//button[@id='select.me.by.id']
CSS Misunderstanding
In CSS we are not saying, “find the id select.me.by.id
”
We are saying “find the id select
with class me
by
id
” which is not at all what we want.
Fortunately CSS offers escaping.
Locate the id using CSS with:
#select\.me\.by\.id
Of course, you could use XPath instead.
Example
@Test
public void cssWithoutEscapingFails(){
driver.get("https://testpages.herokuapp.com/styled/" +
"challenges/hard-selectors.html");
Assertions.assertThrows(NoSuchElementException.class, () ->
driver.findElement(By.cssSelector("#select.me.by.id")));
}
@Test
public void cssEscapingExample(){
driver.get("https://testpages.herokuapp.com/styled/" +
"challenges/hard-selectors.html");
String goodSelector = "#select\\.me\\.by\\.id";
final WebElement button = driver.findElement(
By.cssSelector(goodSelector));
button.click();
Assertions.assertEquals("Event Triggered",
driver.findElement(By.cssSelector(goodSelector + "status")).
getText());
}
Full Source
The full source for this is in my Webdriver Java FAQs project:
Specifically:
If you want to learn how to use Selenium WebDriver with Java then check out our online courses.