isElementPresent in selenium 2.0
Asked Answered
E

7

13

Hello all I am using webdriver so if I want to use selenium;s rc function isElementPresent I have to emulate selenium rc so I do something like this:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class new {
 private static void one_sec() {
  Thread.sleep(4000);
 }
 public static void main(String[] args) {    
  WebDriver driver = new FirefoxDriver();
  driver.get(something1);
  Selenium selenium = new WebDriverBackedSelenium(driver, something1); 
  selenium.click("//html...");
  one_sec();
  System.out.println(selenium.isElementPresent("text"));
  WebDriver driverInstance = ((WebDriverBackedSelenium) selenium).getWrappedDriver();
  ...
  }

and I always get false as result of isElementPresent and of course element "text" is on the web (which is using GWT).

Exeunt answered 7/5, 2011 at 17:50 Comment(1)
Does the text element have it's id as "text"? You have not mentioned any locator prefix to denote whether its xpath or css or dom. Selenium will be looking for an element with @id='text'Debark
B
14

I really like Rostislav Matl's alternative Moving to Selenium 2 on WebDriver, Part No.1:

driver.findElements(By.className("someclass")).size() > 0;

Javadoc: org.openqa.selenium.WebDriver.findElements(org.openqa.selenium.By by)

Bantam answered 12/7, 2011 at 21:38 Comment(2)
I am confused about size() method. Is there any method of WebElement named size()?Transmute
@RiponAlWasim Watch out, size() is a List method. The WebDriver method I'm referring to is findElements, not findElement, and it returns a List<WebElement>. See the signature: WebDriver.findElements(By by) and an example: Locating UI Elements (WebElements) by Class NameBantam
D
8

You can implement it yourself using pure webdriver:

private boolean isElementPresent(By by) {
    try {
        driver.findElement(by);
        return true;
    } catch (NoSuchElementException e) {
        return false;
    }
}
Danettedaney answered 5/7, 2012 at 12:18 Comment(0)
C
3

In the Selenium 2 world, if you want to find if an element is present you would just wrap the find call in a try catch because if it isnt present it will throw an error.

try{
  driver.findElement(By.xpath("//div"));
}catch(ElementNotFound e){
  //its not been found
}
Calley answered 8/5, 2011 at 9:3 Comment(4)
Or driver.findElements( ... ).size() != 0 ; )Darnell
I think, There is no size() method in WebDriver. There is a getSize() method which returns DimensionTransmute
@AutomatedTester: How can I use assertTrue() by using the above codeTransmute
there is size which returns the dimensions and when trying to use size(), I get back TypeError: 'dict' object is not callableSpermic
O
3

Not a part of Selenium 2, you can do the following:

// Use Selenium implementation or webdriver implementation 
Boolean useSel = false;

/**
     * Function to enable us to find out if an element exists or not.
     *
     * @param String An xpath locator
     * @return boolean True if element is found, otherwise false.
     * @throws Exception
     */
    public boolean isElementPresent(String xpathLocator) {
        return isElementPresent(xpathLocator, false, "");
    }

/**
     * Function to enable us to find out if an element exists or not and display a custom message if not found.
     *
     * @param String An xpath locator
     * @param Boolean Display a custom message
     * @param String The custom message you want to display if the locator is not found
     * @return boolean True if element is found, otherwise false.
     * @throws Exception
     */
    public boolean isElementPresent(String xpathLocator, Boolean displayCustomMessage, String customMessage) {
        try {
            if (useSel) {
                return sel.isElementPresent(xpathLocator);
            } else {
                driver.findElement(By.xpath(xpathLocator));
            }
        } catch (org.openqa.selenium.NoSuchElementException Ex) {
            if (displayCustomMessage) {
                if (!customMessage.equals("")) {
                    System.out.print(customMessage);
                }
            } else {
                System.out.println("Unable to locate Element: " + xpathLocator);
            }
            return false;
        }
        return true;
    }
Ogg answered 9/5, 2011 at 12:48 Comment(0)
B
3

Sometimes the element you are trying to find is loading, s0 will throw an exception using

  findElement(By.xpath(xpathLocator))  

Therefore we would need do what Dejan Veternik has recommended, it will help wait until the ELEMENT has been loaded in the webpage, I am passing Selenium and extracting webdriver, this is helpful incase you are using WebDriverBackedSelenium just like me ...

 private boolean isElementPresent(WebDriverBackedSelenium driver, String id) {
        try {
            driver.getWrappedDriver().findElement(By.id(id));
            return true;

        } catch (Exception e) {
            return false;
        }
    }

 
Bulla answered 29/11, 2012 at 23:3 Comment(0)
C
0

I'm using the Node library selenium-webdriver 3.6.0.

It has driver.findElements (return zero or more items) and driver.findElement (returns first item found or throw NoSuchElementError).

So I'd like to recommend this as a check for if at least one element can be found. Perhaps useful in Java.

driver.findElement(By.className("someclass"));
Cartesian answered 13/8, 2019 at 17:11 Comment(0)
M
0

This code works for me. It may not be the most elegant, but it is functional.

Boolean elementExists=true;
    try {
        SoftAssert sAssert = new SoftAssert();
        sAssert.assertTrue (element.isDisplayed());
    }catch (NoSuchElementException e){
        elementExists = false;
    }
    Assert.assertFalse(elementExists);

You have to be careful that "NoSuchElementException" is "org.openqa.selenium" not "java.util" because otherwise, it won't work

Mathison answered 31/1, 2022 at 12:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.