Selenium中的try catch块中的带有isDisplayed()方法的

我想检查阴性情况。上面的boolean元素未显示,但我必须打印true和false,但它没有显示此类元素异常,请帮助。


try{


    boolean k= driver.findElement(By.xpath("xpath_of_element")).isDisplayed();

    if(!k==true)

    {

             System.out.println("true12"); 

    }


}catch (NoSuchElementException e) {

    System.out.println(e);

}


慕容3067478
浏览 348回答 3
3回答

慕斯王

元素有两个不同的阶段,如下所示:HTML DOM中存在的元素元素可见,即显示在DOM树中正如你所看到的NoSuchElementException异常基本上表示该元素不存在的内视口,并在所有可能的条件下isDisplayed()方法将返回错误。因此,要验证这两个条件,可以使用以下解决方案:try{    if(driver.findElement(By.xpath("xpath_of_the_desired_element")).isDisplayed())        System.out.println("Element is present and displayed");    else        System.out.println("Element is present but not displayed"); }catch (NoSuchElementException e) {    System.out.println("Element is not present, hence not displayed as well");}

芜湖不芜

  if (driver.findElements(xpath_of_element).size() != 0) return true;           return false;

慕桂英4014372

在检查元素的显示状态之前,应该使用以下代码验证给定的xpath是否存在至少一个或多个元素。List<WebElement> targetElement =&nbsp; driver.findElements(By.xpath("xpath_your_expected_element"));&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; if(targetElement>=1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(targetElement.isDisplayed()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Element is present");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Element is found, but hidden on the page");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Element not found on the page");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }catch (NoSuchElementException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Exception in finding the element:" + e.getMessage());&nbsp; &nbsp; &nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java