Verifying whether an element present or visible in Selenium Webdriver

SeleniumAutomation TestingTesting Tools

We can verify whether an element is present or visible in a page with Selenium webdriver. To check the presence of an element, we can use the method – findElements.

The method findElements returns a list of matching elements. Then, we have to use the method size to get the number of items in the list. If the size is 0, it means that this element is absent from the page.

Syntax

int j = driver.findElements(By.id("txt")).size();

To check the visibility of an element in a page, the method isDisplayed is used. It returns a Boolean value( true is returned if the element is visible, and otherwise false).

Syntax

boolean t = driver.findElement(By.name("txt-val")).isDisplayed();

Example

Code Implementation for element visible.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class ElementVisible{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element with partial link text
      WebElement n =driver.findElement(By.partialLinkText("Refund"));
      //check if element visible
      boolean t = driver.findElement(By.partialLinkText("Refund")).isDisplayed();
      if (t) {
         System.out.println("Element is dispalyed");
      } else {
         System.out.println("Element is not dispalyed");
      }
      driver.quit();
   }
}

Output

Example

Code Implementation for element presence.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class ElementPresence{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      //check if element present
      int t = driver.findElements(By.partialLinkText("Refund")).size();
      if (t > 0) {
         System.out.println("Element is present");
      }else {
         System.out.println("Element is not present");
      }
      driver.quit();
   }
}

Output

raja
Published on 03-Apr-2021 14:14:44
Advertisements