| by Arround The Web | No comments

How to Check If an Element Exists in Selenium

This post examines how to use the Selenium WebDriver to determine whether an element exists or not. Using some simple and easy examples through coding, we demonstrate how to check the existence of elements in the Selenium WebDriver. First, we explain what important WebElements are in Selenium and how you can find the elements in Selenium with the help of different examples. Let’s first discuss what Selenium WebDrivers and WebElements are.

Selenium WebDriver and Selenium WebElements

Selenium WebDriver made the programmers’ lives easier with its useful features. Selenium WebDriver refers to the language bindings and the many implementations of browser-controlling code. An HTML element is called a WebElement which enables the users to control the automated tests. Through WebElements, Selenium WebDriver offers well-organized web page interactions like finding the elements, obtaining the attribute properties, confirming the text in the WebElement, and more. We can automate a wide variety of testing environments with the guidance of Selenium.

Command to Find an Element in Selenium

The “By” object is a parameter for the Find Element command which delivers an object of the WebElement type. Various locator techniques such as Name, ID, ClassName, XPath, link text, etc. can be used with the “By” object.

Here is the syntax to find an element:

WebElement elementName = driver.findElement(By.LocatorStrategy(“LocatorValue”));

Any of the following values including the Name, ID, Class Name, Tag Name, Link Text, Partial Link Test, and Xpath, can be utilized for Locator Strategy.

Any of these values can be entered into the locator to locate the web element.

How to Verify If an Element Exists in Selenium

Several ways can be adopted to check if a certain element is in the Selenium WebDriver or not. Here is a summary of the most typical ways to find out if the elements exist in the WebDriver or not.

ElementInElement(..) the second getElementsByClassName (..)

ElementInElement contains (elementName, elementValue) (name, value).

The result is Boolean. If the element is present, it produces a bool value of TRUE. Otherwise, it answers FALSE. Providing a null name also produces a true result, while providing a string produces a false result.

Now, to understand this procedure, we will go to our interface and execute some example codes.

Example 1:

This first example is very basic and simple which is created for beginners and experienced level developers. The program starts with importing the driver.find to get the WebElements with the tag name to check the existence of the web elements in it. We provide the following complete command which you can refer to. After that, we explain this code in chunks so that you can understand what action they perform.

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

public class checkIfExists {

public static void main(String[] args)

{

System.setProperty(“webdriver.chrome.driver”, “./drivers/chromedriver.exe”);

WebDriver driver1 = new ChromeDriver();

driver1.get(“http://demoqa.com/registration/”); driver1.manage().timeouts().implicitlyWait(2000,TimeUnit.MILISECONDS);

List<WebElement> dd=driver1.findElements(By.tagName("Select"));

if(dd.size())>0){ System.out.println(“Dropdown exists");

} else

}

}

System.out.println('No dropdown");­­­­

Now, let’s try to understand the previous code.

If we want to verify whether the dropdowns exist or not, we should know where the dropdowns are present in the down structure. If you inspect a dropdown in a particular website, the dropdowns are under the select tags. The screenshot is attached to see where we can find the select tab and dropdown.

If there are any select tags present on the particular web page, the dropdowns are on the page. If there is no present select tag, there are no present or existent dropdowns. So, we need to use this hint:

List<WebElement> dd=driver.findElements(By.tagName(“Select”));

We use the driver.findElements() method to determine whether an element is present on a webpage. As we are aware, a list of webElements is located using the “By Locator” parameter which is returned by the findElements() function. If the element is found, a list of non-zero webElements is returned. Otherwise, a list of size 0 is returned. As a result, the length of the list can be utilized to determine if an entry is present or not.

Keep in mind that when searching for the element, this function waits until the “implicit” wait is given for the driver as we give in our coding:

driver1.manage().timeouts().implicitlyWait(2000,TimeUnit.MILISECONDS);

If we know that an element is immediately available on the webpage, we can change the “implicit” wait’s value back to its default value after setting it to 0, checking for the presence of elements and speeding up the process.

If you only put “select”, you will not be able to get any output. It only goes to the select tag and point it.

That’s all. If you want to verify whether the drop downs exist or not, you should store this output it in the “list webElement” variable.

A picture containing text Description automatically generated

After executing the code, we get the result that a “Dropdown exists” as you can see in the provided illustration.

Example 2:

In the previous example, we used the method of finding an element by Tagname to see if a dropdown element exists or not. Now, from this example onwards, you will know how to find the elements using the try and catch methods.

Let’s execute the code and check how to use it:

System.setProperty(“webdriver.gecko.driver”,“/Users/abc/Desktop/C/DZ/Library/xyz”);

WebDriver driver1 = new FirefoxDriver();

driver1.get(https://www.google.com)

try{

driver1.findElement(By.xpath(“//input[@id=’djahvljadhlkgj’))

System.out.printIn(Element exists);

}

catch(NoSuchElementException e){System.out.printIn(“Element not exist);

}

To check if the element exists or not, we use a try and catch block. All we need to do is try to find the element.

driver.findElement(By.xpath(“//input[@id=’djahvljadhlkgj’]”));

Now, the previous code snippet finds the element using the XPath:

catch(NoSuchElementException e){System.out.printIn(“Element not exist);}

Now, if the element is not found in the catch block, it means that there is no element present on the page with this kind of locator in this Xpath. Then, the error is caught so we can catch the exception.

Text Description automatically generated with low confidence

After running the code, it throws the “No Such Element Exception” error. This is what we want to recover in the catch block:

try{

drive1r.findElement(By.xpath(“//input[@id=’djahvljadhlkgj’))

System.out.printIn(Element exists);

}

catch(NoSuchElementException e){System.out.printIn(“Element not exist);

}

What we did is that we took a try block. In that try block, we find out the element which we want to find using whatever locator we want to use. If the element is found, it simply executes and the statement says that the element exists and it never goes to the catch block. If the element is not found, it throws no such element. Then, it simply executes the “Element Not Found” in the catch block.

Example 3:

In this instance, we use the driver.find elements by id. Then, we get the count of that particular element. If it is not zero, it means that the element is present. Always try the find elements, not the find element. The difference between the two is that if you use the find element, it throws the “No Such Element Found” exception. But the find elements do not throw this exception even if the element is present or not. Just remember to use this find elements method and check the count of that value or that list of that element. If the count is 0, that means that the element is not present.

if (driver1.findElements(By.Id(“abc”)).Count!=0)

console.WriteLine(“Element is present”);

else

console.WriteLine(“Element is not present”);

In this code, we receive the count of 0 which means that the element is not present.

Conclusion

We discussed about using coding to determine whether the elements in Selenium WebDriver exist or not. The idea of the parameter to find the element command which returns an object of the WebElement type is shown here from the examples. In this article, we understand the concept of how to find the existence of web elements in Selenium WebDrivers using different methods. You can refer to this article from the start to the end to better understand the whole concept.

Share Button

Source: linuxhint.com

Leave a Reply