Java If语句不';无法在ID存储为字符串变量的Selenium WebDriver中工作
我面临下一个问题: 代码示例:Java If语句不';无法在ID存储为字符串变量的Selenium WebDriver中工作,java,selenium,junit,Java,Selenium,Junit,我面临下一个问题: 代码示例: 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));
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语句中使用字符串变量时,脚本运行时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'
isElementPresent(By)是一个自定义方法,但它没有任何问题。我还尝试了driver.findElements本机方法,结果相同:
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));
}
String dispSys=“故意\u错误\u ID”;
if(driver.findElements(By.id(dispSys)).size()<1){
collector.addError(新的可丢弃文件(“错误:”+PDS\U lbl\U txt+“*第页未找到标签”);
}否则{
collector.checkThat(PDS_lbl.getText(),equalTo(PDS_lbl_txt));
}
如果你能给我一点建议,我将不胜感激。谢谢。您可以将iElementPresent改写为以下内容:
public boolean isElementPresent(String elementId) {
try {
driver.findElement(By.id(elementId)).isDisplayed();
return true;
} catch (NoSuchElementException ignored) {
return false;
}
}
你能分享一下isElementPresent的方法吗?我在这里得到了答案:谢谢你的回答,但“isElementPresent”不是重点。另外,出于某些原因(如此),我不是“.isDisplayed()”的超级粉丝。关键是我不明白为什么我存储ID的方式会影响IF语句。