繁体   English   中英

Selenium WebDriver Java - 如何执行“如果存在,则单击,否则跳过”?

[英]Selenium WebDriver Java - how to perform "if exists, then click, else skip"?

在我的页面上,有时会显示警报。 (这些实际上是 Salesforce 中的通知)这些警报破坏了我的脚本,因为我的脚本无法找到警报背后的元素。 我想检查警报,如果它们存在,请关闭它们。 如果它们不存在,则继续下一步。

次要问题是这些警报可能不止一个。 因此,它可能会解除 1 到 6 个或更多警报。

我已将此代码添加到我的测试脚本中,如果有一个警报,它就可以工作。 显然,如果有多个警报或零警报,我的脚本将失败。

driver.findElement(By.xpath("//button[contains(@title,'Dismiss notification')]")).click();

我还在学习java,所以请温柔。 ;) 但我很想把它放到一个方法中,这样它就可以查找那些按钮,如果它们存在就点击,继续寻找更多直到找不到,然后继续。 我只是不知道该怎么做。

我也在使用 TestNG,我知道这在允许和不允许的方面有所不同。

谢谢!

您可以使用 wait 和 try/catch 来获取所有按钮并单击每个按钮(如果存在)。

1.如果警报同时出现,请使用以下代码:

try{
      new WebDriverWait(driver, 5)
              .ignoring(ElementNotVisibleException.class, NoSuchElementException.class)
              .until(ExpectedConditions.visibilityOfAllElements(driver.findElements(By.cssSelector("button[title*='Dismiss notification']"))))
      .forEach(WebElement::click);
} catch (Exception ignored){ }

2.如果单独出现警报,请使用以下代码:

try{
    while(true) {
        new WebDriverWait(driver, 5)
                .ignoring(ElementNotVisibleException.class, NoSuchElementException.class)
                .until(ExpectedConditions.visibilityOf(driver.findElement(By.cssSelector("button[title*='Dismiss notification']"))))
                .click();
    }
} catch (Exception ignored){ }

使用findElements如果元素不存在,它将返回 0 的列表。

例如:

List<WebElement> x = driver.findElements(By.xpath("//button[contains(@title,'Dismiss notification')]"));

if (x.size() > 0)
{
    x.get(0).click();
}
// else element is not found.

findElements将返回列表,无需再次创建。 x.size()也不起作用,因为列表对象没有属性 size 所以我们必须检查长度。 不需要使用x.get(0).click(); .

driver.click(By.xpath("//button[contains(@title,'Dismiss notification')]"))应该可以工作。

x = driver.findElements(By.xpath("//button[contains(@title,'Dismiss notification')]"));

if (len(x) > 0) {
  x.click();
}

暂无
暂无

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

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