Sohel
Sohel

Reputation: 676

Java Selenium - Searching Using xpath not finding searched element

Here are two code segments that I'm using to search for dates from a Calendar that has "From Date" and "To Date".

        webDriver.findElement(By.xpath("//table/tbody/tr/a[contains(text(),'October 30')]")).click();

        webDriver.findElement(By.xpath("//table/tbody/tr/a[contains(text(),'October 31')]")).click();

Error message shows: Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//table/tbody/tr/a[contains(text(),'October 30')]"}

Code segment image: code segment Please kindly help. Thank you.

Upvotes: 1

Views: 601

Answers (2)

Rajkumar
Rajkumar

Reputation: 58

Don't rely on dates. It is unstable because from date and to date are not fixed dates. It may change for each and every records.

Upvotes: 1

alecxe
alecxe

Reputation: 473763

Two things to fix (at least):

  • the a element is not a direct child of tr, there is one more level - the td element
  • you need to check the title attribute and not the text()

Fixed version:

//table/tbody/tr/td/a[contains(@title, 'October 30')]

Or, with a strict equality check:

//table/tbody/tr/td/a[@title = 'October 30']

Or, avoiding checking the parents:

//a[@title = 'October 30']

Or, alternatively, you may also try going with a bit more concise CSS selector:

webDriver.findElement(By.cssSelector("a[title='October 30']")).click();

Upvotes: 1

Related Questions