Selenium: How to identify element within a if statement?

Viewed 279

Using Selenium in Visual Studio. I'm writing a testcase where I first need to see if a specific element exist or not before I can proceed.

When I try to identify an element within a if-statement like this:

  if (driver.FindElement(By.XPath("//lina-device-information/div[1]/div[2]/lina-list-wrapper[3]/div/div/lina-insurance-information")))
{
//Do stuff
}
else
{
//End test
}

I get an error: "Error CS0029 Cannot implicitly convert type 'OpenQA.Selenium.IWebElement' to 'bool' "

Is it not possible to use FindElement as a condition within a if-statement or what am I doing wrong?

2 Answers

If the element is not present in DOM then it will throw NoSuchElementException when using findElement.
Try using findElements which returns a list. Then check if the list is empty or not. This way you don't have to handle the exception.

Try this:

if (driver.FindElements(By.XPath("//lina-device-information/div[1]/div[2]/lina-list-wrapper[3]/div/div/lina-insurance-information")).Count > 0)
 {
 // Do stuff
 // Element found
 }
 else{
 // Element not found
 }

'If' expects a boolean expression, instead of boolean, 'FindElement' is returning a webElement. Hence you are thrown a compile time error.

Related