【问题标题】:try catch is not working on isDisplayed() in selenium and throwing stry catch 不适用于 selenium 中的 isDisplayed() 和 throwing s
【发布时间】:2021-11-02 10:36:42
【问题描述】:

页面上没有元素!

代码如下:

try {
        if (driver.findElement(By.xpath("(//*[text()='Duplicate Saved Filter'])")).isDisplayed()) {
   
            driver.findElement(By.xpath("(//*[text()=' Yes '])")).click();
            Thread.sleep(2000);
    }} catch (NoSuchElementException e) {
        logger.info("element not found");
        }

【问题讨论】:

  • 在某些情况下元素存在但不可见,在这种情况下,如果我使用 .size>0 方法,我也会抛出错误,这就是我使用 isDisplayed 的原因。跨度>
  • 这听起来像是X-Y problem。与其寻求解决问题的帮助,不如编辑您的问题并询问实际问题。你想做什么?
  • @DebanjanB 我想做的是,如果找到元素,它应该运行条件。如果没有找到,它应该捕获异常并继续代码而不是抛出错误。
  • 如果页面上没有元素,isDisplayed() 代替常规的findElement() 有何帮助?
  • 嗯,我听不懂你在说什么。你能解释一下吗?谢谢

标签: java selenium selenium-webdriver


【解决方案1】:

你想要什么:

  • 如果元素存在且可见,请单击是
  • 否则记录一些东西,不会抛出错误

这里的技巧是使用 findElementS(注意 S)。这给出了一个找到元素的列表,如果 0 比没有元素(防止错误抛出)。 如果有元素,检查它是否显示。 根据您的评论,我猜您尝试使用 findElementS 但忘记添加 .size() > 0 检查。

List<WebElement> elements = driver.findElements(By.xpath("(//*[text()='Duplicate Saved Filter'])"));
if(elements.size() == 0) {
    logger.info("element not found");
} else if(!elements[0].Displayed())) {
    logger.info("element not visisble");
} else {
    driver.findElement(By.xpath("(//*[text()=' Yes '])")).click();
    Thread.sleep(2000);
}

【讨论】:

  • 我认为你的答案与我已经做过的很接近。复制粘贴到记事本中,让我知道您对此有何看法。
猜你喜欢
  • 2018-12-02
  • 2012-05-14
  • 2017-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多