如何在Java-Selenium中不使用findElement()或findElements()来检查元素是否存在?

huangapple go评论88阅读模式
英文:

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

问题

情景是:

  1. 在Selenium中查找一个元素,但不使用findElement()或findElements()方法。
  2. 代码不应抛出任何异常。相反,如果找到元素,则打印“找到元素”,否则打印“未找到元素”(而不是打印,可以执行任何希望执行的操作)。
英文:

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).

答案1

得分: 5

为了查找元素是否存在,我在selenium-java中使用了JavascriptExecutor。

以下是代码。我已经使用了document.getElementById(id)来演示解决方案,您可以使用其他方法,如document.getElementsByTagName(name)document.getElementsByClassName(className)等。为了演示,我使用了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("Element not Found");

driver.close();
英文:

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();

huangapple
  • 本文由 发表于 2020年9月15日 14:57:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63896654.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定