Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if Element exists in c# Selenium drivers

Tags:

c#

selenium

So I have this c# winform using Firefox selenium webdriers.

Basically i need it to check if an element exists and if it doesn't click on a different one. If there is a video and after it is watched it become W_VIEWED

Here is what i got so far

driver.FindElement(By.XPath("//div[@class='video']/a")).Click();
else {
          driver.FindElement(By.XPath("//div[@class='W_VIEWED']/a")).Click();
     }

Error 3 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement 242

Kind of new to c# selenium. Thank you for help.

like image 253
Programerszz Avatar asked Dec 17 '14 00:12

Programerszz


People also ask

How do you check if an element exists in an array in C?

To check if given Array contains a specified element in C programming, iterate over the elements of array, and during each iteration check if this element is equal to the element we are searching for.

How do you check if an element is present in an array CPP?

Use the any_of() Function to Check if an Array Contains an Element in C++ We can use the any_of() function to check if a predicate conforms to any elements present in a given range. If yes, it returns true ; else, it returns false .

How do you check if an element is not in an array C++?

A simple and elegant solution is to use the std::find function to find a value in an array. It returns an iterator to the first occurrence of the matching element, or an iterator to the end of the range if that element is not found.


2 Answers

You can check element exits or not using

bool isElementDisplayed = driver.findElement(By.xpath("element")).isDisplayed()

Remember, findElementthrows exception if it doesn't find element, so you need to properly handle it.

In one of my application I handled exception by checking element in separate function :

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

Call function :

if (IsElementPresent(By.Id("element name")))
{
    //do if exists
}
else
{
    //do if does not exists
}

like image 178
Pranit Kothari Avatar answered Oct 17 '22 03:10

Pranit Kothari


You can use FindElements with an "s" to determine if it exists, since FindElement results in an Exception. If FindElements does not return an element then it returns an empty list.

List<IWebElement> elementList = new List<IWebElement>();
elementList.AddRange(driver.FindElements(By.XPath("//input[@att='something']")));

if(elementList.Count > 0)
{
 //If the count is greater than 0 your element exists.
   elementList[0].Click();
}
like image 32
Dominic Giallombardo Avatar answered Oct 17 '22 04:10

Dominic Giallombardo