Java 如何在 selenium webdriver 中使用 if/else 条件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21249140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use if/else condition in selenium webdriver?
提问by testing
In selenium webdriver i want to use if/else condition with java. Each steps need to be checked and need to execute one by one. For example
在 selenium webdriver 中,我想在 java 中使用 if/else 条件。每一步都需要检查,需要一一执行。例如
Log.info("Clicking on Reports link");
WebElement menuHoverLink = driver.findElement(By.id("reports"));
actions.moveToElement(menuHoverLink).perform();
Thread.sleep(6000);
In this code, i need to check the id once it present it need to perform the action else it need to skip the test case not to be failed.
在这段代码中,我需要检查 id 一旦它出现就需要执行操作,否则它需要跳过测试用例才不会失败。
采纳答案by Dilip Kumar
if(driver.findElement(By.id("reports").size()!=0){
WebElement menuHoverLink = driver.findElement(By.id("reports"));
actions.moveToElement(menuHoverLink).perform();
}
else{
system.out.println("element not present -- so it entered the else loop");
}
use this one -- if the element is not persent also testcase doesnt fail
使用这个——如果元素不存在,测试用例也不会失败
回答by Yuvaraj HK
Use try catch block in your script like
在脚本中使用 try catch 块,例如
Log.info("Clicking on Reports link");
try {
WebElement menuHoverLink = driver.findElement(By.id("reports"));
actions.moveToElement(menuHoverLink).perform();
Thread.sleep(6000);
} Catch(Exception e) {
// Element not found....do not fail my test
}
回答by barak manos
Option #1:
选项1:
WebElement menuHoverLink = null;
try
{
menuHoverLink = driver.findElement(By.id("reports"));
}
catch(Exception e)
{
}
if (menuHoverLink != null)
{
actions.moveToElement(menuHoverLink).perform();
Thread.sleep(6000);
}
Option #2:
选项#2:
List<WebElement> menuHoverLinks = driver.findElements(By.id("reports"));
if (menuHoverLinks.size() > 0)
{
actions.moveToElement(menuHoverLinks.get(0)).perform();
Thread.sleep(6000);
}
Keep in mind that Thread.sleep
by itself may also throw an exception, so you should either catch it inside the method, or add throws Exception
at the end of the method's declaration.
请记住,Thread.sleep
它本身也可能引发异常,因此您应该在方法内部捕获它,或者throws Exception
在方法声明的末尾添加。
回答by Dilip Kumar
Try this one . i think this should work
for me it worked
private boolean existsElement(String id) {
try {
driver.findElement(By.id(id));
} catch (Exception e) {
System.out.println("id is not present ");
return false;
}
return true;
}
if(existsElement("reports")==true){
WebElement menuHoverLink = driver.findElement(By.id("reports"));
actions.moveToElement(menuHoverLink).perform();
}
else{
system.out.println("element not present -- so it entered the else loop");
}