Swapnil Kotwal
Swapnil Kotwal

Reputation: 5720

Selenium not able to locate element in browser DOM

I have a tests suite where I must have to use css selectors.

When I make a query through selenium

driver.findElement(By.cssSelector("#credentials.errors"));

OR

if (driver instanceof JavascriptExecutor) {
      ((JavascriptExecutor) driver).executeScript("document.
        getElementById('credentials.errors');");
    }

OR

If I search for #credentials.errors manually in browser csspath query

It's simply not able to locate element but I can locate that element in browser console by making query

document.getElementById('credentials.errors')

My question is if element can located by JavaScript console then why not by selenium webdriver?

Upvotes: 2

Views: 1243

Answers (3)

John
John

Reputation: 9

Since you are using an ID to find the element you could use the following instead of using the By.cssSelector:

driver.findElement(By.Id("credentials.errors"));

Upvotes: 0

BoltClock
BoltClock

Reputation: 723448

The selector #credentials.errors looks for an element with the ID "credentials" and a class "errors", not an element with the ID "credentials.errors". The dot is being interpreted as the start of a class selector. In other words, it's equivalent to .errors#credentials, with both simple selectors swapped around.

document.getElementById() works because it simply takes a string as the input ID. It does not try to parse it as a compound selector.

To correctly locate the element with an ID selector, you need to escape the dot:

driver.findElement(By.cssSelector("#credentials\\.errors"));

You can also use an attribute selector instead so you don't have to escape anything:

driver.findElement(By.cssSelector("[id='credentials.errors']"));

Upvotes: 2

Sutanto
Sutanto

Reputation: 28

Maybe the element created by client side script after Ajax calling, so you need to wait using WebDriverWait

Upvotes: 0

Related Questions