我有一种情况,页面将我带到屏幕上并显示一条消息,例如未启用该功能。因此你在这里。 然后,我需要导航到设置页面并必须启用它并重新加载表单以验证Web元素。
最初,一切正常,第二次运行代码。我没有遇到这样的元素异常。 因为该设置最初是被禁用的,所以已通过自动脚本启用了该设置,现在已启用,我可以看到表单元素。仅当找到该元素时,我才必须执行系统设置代码,否则我必须跳过该代码。
我尝试下面的方法,但是仍然找不到这样的元素错误
if(driver.findElement(By.id("ViewErrorMessage")) != null) {
String errorMsg = driver.findElement(By.xpath("//*[@id=\"ctl00_pnlViewErrorMessage\"]")).getText();
Assert.assertEquals(errorMsg, "Form is disabled, Hence you are here. Enable the form");
//system setting code
driver.findElement(By.xpath("//input[@name='btnSignin']")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//img[@id='imgLogo']")).isDisplayed();
}else{
//code to verify form elements goes here..
}
在if条件下报告错误。 当找不到元素时,我假设它必须执行else循环,但总是在同一点失败。谁能帮忙。
答案 0 :(得分:0)
当驱动程序找不到元素时,它将引发NoSuchElementFound异常。您可以将findElement包裹在try catch中以查看该元素是否存在,也可以使用isEmpty方法。
boolean isElementPresent=true;
try
{
driver.findElement(By.id("ViewErrorMessage"));
}
catch
{
isElementPresent=false;
}
if(isElementPresent) {
String errorMsg = driver.findElement(By.xpath("//*[@id=\"ctl00_pnlViewErrorMessage\"]")).getText();
Assert.assertEquals(errorMsg, "Form is disabled, Hence you are here. Enable the form");
//system setting code
driver.findElement(By.xpath("//input[@name='btnSignin']")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//img[@id='imgLogo']")).isDisplayed();
}else{
//code to verify form elements goes here..
}
或者您可以喜欢
if(!driver.findElements(By.id("ViewErrorMessage")).isEmpty()) {
String errorMsg = driver.findElement(By.xpath("//*[@id=\"ctl00_pnlViewErrorMessage\"]")).getText();
Assert.assertEquals(errorMsg, "Form is disabled, Hence you are here. Enable the form");
//system setting code
driver.findElement(By.xpath("//input[@name='btnSignin']")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//img[@id='imgLogo']")).isDisplayed();
}else{
//code to verify form elements goes here..
}
答案 1 :(得分:0)
请尝试在条件中显示isDisplay,希望这会有所帮助:
if(driver.findElement(By.id("ViewErrorMessage").isDisplayed()) {
String errorMsg = driver.findElement(By.xpath("//*[@id=\"ctl00_pnlViewErrorMessage\"]")).getText();
Assert.assertEquals(errorMsg, "Form is disabled, Hence you are here. Enable the form");
//system setting code
driver.findElement(By.xpath("//input[@name='btnSignin']")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//img[@id='imgLogo']")).isDisplayed();
}else{
//code to verify form elements goes here..
}
或在下面使用
String s1 = "Error message";
String s2 = driver.findElement(By.id("ViewErrorMessage").getText());
if(s1 == s2) {
String errorMsg = driver.findElement(By.xpath("//*[@id=\"ctl00_pnlViewErrorMessage\"]")).getText();
Assert.assertEquals(errorMsg, "Form is disabled, Hence you are here. Enable the form");
//system setting code
driver.findElement(By.xpath("//input[@name='btnSignin']")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//img[@id='imgLogo']")).isDisplayed();
}else{
//code to verify form elements goes here..
}