Selenium Webdriver,检查是否启用了多个元素,如果为真则与它们交互

Selenium Webdriver, check if multiple elements are enabled and interact with them if true

我有一个包含 16 个相同 WebElements(按钮)的页面,页面上可能存在也可能不存在。这些按钮具有相同的功能 - 单击时删除一条数据。我需要:-

  1. 检查元素是否对用户可见
  2. 如果 1. 为真,点击它们删除

我目前的代码:-

public void removeExistingPeriods() {

    List<WebElement> removeButtons = driver.findElements(By.cssSelector(".activeLink.removeBtn.btn.btn-warning"));
    if (removeButtons.size() == 0) {
        fail("No Remove buttons were found on the page!:");
    } else {
        for(WebElement option: removeButtons){
            option.click();
        }
    }

}

这失败了:- org.openqa.selenium.ElementNotVisibleException:元素当前不可见,因此可能无法与

交互

我怎样才能:-

  1. 检查总共 16 个按钮中启用了多少个按钮?
  2. 依次单击那些已启用的按钮,直到没有更多已启用的按钮出现?

尝试 this.Using 增强的 for 循环,您循环遍历 removedButtons 中的每个 WebElement。如果按钮 isDisplayed 然后单击它。

List<WebElement> removeButtons = driver.findElements(By.cssSelector(".activeLink.removeBtn.btn.btn-warning"));
for(WebElement button : removeButtons) {
  if(button.isDisplayed()) {
     button.click();
  }
}

这会起作用:

public void removeExistingPeriods() {

List<WebElement> removeButtons = driver.findElements(By.cssSelector(".activeLink.removeBtn.btn.btn-warning"));
if (removeButtons.size()> 0 && removeButtons.isDisplayed()) {

        for(WebElement option: removeButtons){
        option.click();
      } 
      else 
      {

          fail("No Remove buttons were found on the page!:");


         }
      }

     }

我刚刚reverse if结果和按钮检查条件。

我希望您正在寻找启用的元素列表。下面的代码可以帮助你

int totalEnabledElements = 0;

    try{

        List<WebElement> removeButtons = driver.findElements(By.cssSelector(".activeLink.removeBtn.btn.btn-warning"));
        if(removeButtons.size()>0){

            for(int i=0; i<removeButtons.size(); i++){

                if(removeButtons.get(i).isEnabled()==true){

                    removeButtons.get(i).click();
                    totalEnabledElements++;

                }else{
                    System.out.println("element not visible or hidden :" +removeButtons.get(i).getText());
                }

            }

            System.out.println("total enabled elements: " +totalEnabledElements);

        }else{

            System.out.println("No Remove buttons were found on the page!");
        }

    }catch(Exception e){
        System.out.println(e.getStackTrace());
    }

在上面的代码中使用了 isEnabled() 正如你所说的启用元素,如果你打算检查显示的元素那么你可以使用 isDisplayed。

如果我错了,请告诉我。

谢谢, 穆拉利