如何在selenium webdriver中使用if / else条件?

时间:2014-01-21 04:23:32

标签: java selenium-webdriver

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

在这段代码中,我需要检查id一旦出现它需要执行操作,否则它需要跳过测试用例不会失败。

4 个答案:

答案 0 :(得分:2)

选项#1:

WebElement menuHoverLink = null;
try
{
    menuHoverLink = driver.findElement(By.id("reports"));
}
catch(Exception e)
{
}
if (menuHoverLink != null)
{
    actions.moveToElement(menuHoverLink).perform();
    Thread.sleep(6000);
}

选项#2:

List<WebElement> menuHoverLinks = driver.findElements(By.id("reports"));
if (menuHoverLinks.size() > 0)
{
    actions.moveToElement(menuHoverLinks.get(0)).perform();
    Thread.sleep(6000);
}

请记住,Thread.sleep本身也可能会抛出异常,因此您应该在方法中捕获它,或者在方法声明的末尾添加throws Exception

答案 1 :(得分:2)

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

}

使用这个 - 如果元素不存在,测试用例也不会失败

答案 2 :(得分:1)

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

}

答案 3 :(得分:0)

在脚本中使用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
}