Selenium Webdriver C # How to check element is not?

This element can be found when the filled field is filled:

IWebElement e1SK = Driver.Instance.FindElement(By.XPath(baseXPathSendKeys + "div[2]/textarea"));

      

If the required field is not filled, the above item must not be present.

The test throws an exception:

OpenQA.Selenium.ElementNotVisibleException: The element is not currently visible and therefore cannot interact with

Is this something I need to create a method or is it even easier? If you could show an example it would be helpful, I am still pretty new to C # and Selenium Webdriver.

I read that I could use a user called findwebelements and then check that the result is zero, but I'm not sure how to implement this.

+4


source to share


3 answers


Here's a simple approach to the problem:

if (Driver.Instance.FindElements(By.XPath(baseXPathSendKeys + "div[2]/textarea")).Count != 0)
{
    // exists
}
else
{
    // doesn't exist
}

      

You can create a method Exists(By)

to test items:



public bool Exists(By by)
{
    if (Driver.Instance.FindElements(by).Count != 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

      

Then call it when you want to test something:

By by = By.XPath(baseXPathSendKeys + "div[2]/textarea")
if (Exists(by))
{
    // success
}

      

+12


source


I had a weird case where selenium did not throw a NoSuchElementException, but the MakeHttpRequest timed out.

So I came to the conclusion that I got the innerHTML attribute of the parent HTML element and claim that it does not contain the unnecessary element.



   Assert.IsTrue(!parent.GetAttribute("innerHTML").Contains("notWantedElement"));

      

0


source


You can use the below code snippet. If you are writing logic in a step definition method, then the code below will come in handy because nesting the method is not recommended.

Boolean notpresent;

   Try
                       {
                           IWebElement element = Driver.FindElement(By.XPath("Element XPath"));
                       }
                      catch (NoSuchElementException)
                        {
                          elementnotpresent=true;
                        }
                        if (elementnotpresent == true)
                        {
                            Console.WriteLine("Element not present");
                        }
                        else
                        {
                            throw new Exception("Element is present");
                        }

      

0


source







All Articles