繁体   English   中英

硒WebDriver上的“ isDisplyed”无法检查WebElement是否存在

[英]Cannot check the WebElement is Present or Not by “isDisplyed” on selenium WebDriver

我正在尝试使用(By.id)locator.getAtrribute(“ value”)从UI获取值,

问题:

但是,当未找到xpath(UI上不存在Web元素)时,我需要将值设为“ 00:00”,但会收到错误消息“ No Such element”

我需要添加一个检查,以找到UI上存在的webelement,如果为true,则使用getattribute(“ value”)获取值,否则将值返回为'00:00'

但是,当使用If条件时,尽管UI上存在Web元素,“(WebelementforUIvalue.isEmpty()”会返回“ 00:00”。(当UI上没有找到/存在任何元素时,我需要取00:00)

String WebelementforUIvalue = driver.findElement(By.id("ctl00_MainContent_AllowanceGridView_SRow"+cellRosterPerioddd+cellRosterPeriodmm+"_"+PayBucket)).getAttribute("value");
if (WebelementforUIvalue.isEmpty()) {
    UIValue = "00.00";  
} else {
    UIValue = WebelementforUIvalue;   
} 
System.out.println(UIValue);

我个人会在这种情况下使用try / catch块。

try {
    String WebelementforUIvalue = driver.findElement(By.id("ctl00_MainContent_AllowanceGridView_SRow"+cellRosterPerioddd+cellRosterPeriodmm+"_"+PayBucket)).getAttribute("value");
    UIValue = WebelementforUIvalue;
    } 
    catch (NoSuchElementException) {
        UIValue ="00.00";
    }

像这样尝试( Java代码 )。

    try{
       WebElement element = new WebDriverWait(driver,20).until(ExpectedConditions.presenceOfElementLocated(By.id("ctl00_MainContent_AllowanceGridView_SRow"+cellRosterPerioddd+cellRosterPeriodmm+"_"+PayBucket));
       UIValue = element.getAttribute("value");
    }catch(Throwable e){
       UIValue = "00.00";
    }
System.out.println(UIValue);

我已经明确指定了20秒的超时时间。 因此,硒将尝试在20秒内检测到元素的存在。 如果找不到,它将超时,并将分配的“ UIValue”发送给“ 00.00”,否则,如果找到该元素,它将把“值”属性的内容分配给“ UIValue”。

你可以这样尝试...

String WebelementforUIvalue = null;
try{
    WebelementforUIvalue = driver.findElement(By.id("ctl00_MainContent_AllowanceGridView_SRow"+cellRosterPerioddd+cellRosterPeriodmm+"_"+PayBucket)).getAttribute("value");
   } catch(NoSuchElementException nsee) {
           WebelementforUIvalue = "0.0";
   }
System.out.println(WebelementforUIvalue);

您可以使用“ findElements”(末尾观察者为“ s”)以更好的方式处理此问题。 findElements返回与定位条件匹配的元素列表。

List<WebElements> list=driver.findElements(By.id("Your criteria"))
Integer intNoValues=list.size();
if(intNoValues=0)
{  
  UIValue = "00.00";
}
else
{
 UIValue = WebelementforUIvalue;
}

如果您想对findElements进行详细说明,可以观看以下视频如何使用WebDriver查找不存在的元素

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM