简体   繁体   中英

How to check the presence of an element without using findElement() or findElements() in java-selenium?

The scenario is to

  1. Find an element in selenium without using findElement() or findElements() method.
  2. The code should not throw any exception. Instead, if the element is found print element found else print element not found. (Instead of printing one could do whatever he/she wants to).

In order to find the element is present or not, I used JavascriptExecutor in selenium-java.

Below is the code. I have demonstrated the solution using document.getElementById(id) one could you use the other methods like document.getElementsByTagName(name) or document.getElementsByClassName(className) etc.,. For demonstration I have used http://automationpractice.com/index.php

        System.setProperty("webdriver.chrome.driver", "chromedriver_path");
        WebDriver driver = new ChromeDriver();

        driver.get("http://automationpractice.com/index.php");
    
        JavascriptExecutor js = (JavascriptExecutor) driver;
        boolean found = (boolean) js.executeScript(
                "var element = document.getElementById(\"search_query_top\"); if(typeof(element) != 'undefined' && element != null){return true ;}else{return false;}");
        if(found)
            System.out.println("Element Found");
        else
            System.out.println("Elemnet not Found");
        
        driver.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM