我遇到了下一个问题:
代码示例:
if (!driver.isElementPresent(By.id("intentionally_wrong_ID"))) {
collector.addError(new Throwable("Error: *"+PDS_lbl_txt+"* label not found on page."));
} else {
collector.checkThat(PDS_lbl.getText(), equalTo(PDS_lbl_txt));
}
上面的示例按预期工作:
java.lang.Throwable: Error: *Dispense System* label not found on page.
但是当我尝试在 By.id 语句中使用 String 变量时,脚本运行时 IF 条件不起作用:
String dispSys = "intentionally_wrong_ID";
if (!driver.isElementPresent(By.id(dispSys))) {
collector.addError(new Throwable("Error: *"+PDS_lbl_txt+"* label not found on page."));
} else {
collector.checkThat(PDS_lbl.getText(), equalTo(PDS_lbl_txt));
}
结果:
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"intentionally_wrong_ID"}
Command duration or timeout: 11.78 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.45.0', revision: '5017cb8e7ca8e37638dc3091b2440b90a1d8686f', time: '2015-02-27 09:10:26'
driver.isElementPresent(By) 是自定义方法,但没有任何问题。我还尝试了 driver.findElements native 方法,结果相同:
String dispSys = "intentionally_wrong_ID";
if (driver.findElements(By.id(dispSys)).size() < 1) {
collector.addError(new Throwable("Error: *"+PDS_lbl_txt+"* label not found on page."));
} else {
collector.checkThat(PDS_lbl.getText(), equalTo(PDS_lbl_txt));
}
如果您能告诉我如何解决这个问题,我将不胜感激。谢谢。
最佳答案
您可以将 isElementPresent 重写为如下所示:
public boolean isElementPresent(String elementId) {
try {
driver.findElement(By.id(elementId)).isDisplayed();
return true;
} catch (NoSuchElementException ignored) {
return false;
}
}
关于java - 如果语句在 ID 存储为字符串变量的 Selenium WebDriver 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30195942/