1

I am using Selenium v3.8.0, also I do the coding in C#.

Now I try to validate if XPath or the webElement exists on the site, though I don't success

Now I try to validate the text Login

then I want to alert it in console:

Here is my attempt:

 if (IsElementPresent(By.XPath("//h3[@translate='TITLE_LOGIN']"))) {
       Console.WriteLine("Element exists");         
 }
 else {                    
       Console.WriteLine("Element not displayed");            
 }

 private bool IsElementPresent(By by) {
       try
       {
           Driver.Instance.FindElement(by);
           return true;
       }
       catch (NoSuchElementException)
       {
           return false;
       }
 }

see picture below: Picture 1

Link to URL: Owasp Juiceshop

1
  • I was able to find the Login element with document.evaluate("//h3[@translate='TITLE_LOGIN']", document, null, XPathResult.ANY_TYPE, null ) on the Firefox console. Could you display the errors/outputs of your C# code? Commented Jan 20, 2018 at 16:05

2 Answers 2

4

Try this:

bool IsPresent= driver.FindElement(By.XPath("/html/body/main/div/section/h3")).Displayed;
if (IsPresent)
{
     Console.WriteLine("Element exists");
}
else
{
   Console.WriteLine("Element not displayed");
}
0
-1

By using Displayed or (isDisplayed() method in Java) we may get NoSuchElementException

In order to avoid the exception, we may use the below code:

List<WebElement> element = driver.findElements(<By locator>);

if(element.size()>0)
{
  Console.WriteLine("Element exists");
}
else
{
  Console.WriteLine("Element not displayed");
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.