shprei
shprei

Reputation: 55

What is the best way to check if element exist on page?

I have a table with cells containing data, on which i do operations. I am simply checking condition like:

(ExtractTextFromElement(duoqTable, duoqRowNumber, 3, "'duoqTable'").Contains("Europe") ||
  ExtractTextFromElement(duoqTable, duoqRowNumber, 3, "'duoqTable'").Contains("Russia")

The problem is that this IWebElement sometimes may disappear and if I am inside this condition block, the exception occurs. I could do additional check, if the element exists before every condition statement but it seems ineffective. Is there any better way?

Upvotes: 0

Views: 139

Answers (1)

Murthi
Murthi

Reputation: 5347

if you use find Elements method instead of find Element then you will not get exception. Find Elements returns list of Web Elements you need to check the size of it.

if driver.findElements(By.className("xyz").size()>0
   driver.findElements(By.className("xyz").get(0).getText();
else
   System.out.println("No element found")

The above code will not throw any exception and no need to use try/catch block.

Upvotes: 2

Related Questions