英文:
How to check the presence of an element without using findElement() or findElements() in java-selenium?
问题
情景是:
- 在Selenium中查找一个元素,但不使用findElement()或findElements()方法。
- 代码不应抛出任何异常。相反,如果找到元素,则打印“找到元素”,否则打印“未找到元素”(而不是打印,可以执行任何希望执行的操作)。
英文:
The scenario is to
- Find an element in selenium without using findElement() or findElements() method.
- 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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论