Selenium WebDriver Java - how to perform “if exist

2019-08-24 10:06发布

问题:

On my page, I have alerts that display sometimes. (these are actually notifications in Salesforce) These alerts break my scripts since my scripts can't find the elements behind the alerts. I'd like to check for the alerts and if they exist, dismiss them. If they don't exist, then move on to the next step.

Secondary problem is that there may be more than one of these alerts. So it may have dismiss anywhere from 1 to 6 or more alerts.

I've added this code to my test script and it works if there is ONE alert. Obviously my script fails if there is more than one alert or if there are zero alerts.

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

I'm still learning java, so please be gentle. ;) But I'd love to put this into a method so it can look for those buttons, click if they exist, keep looking for more until it finds none, then move on. I just have no idea how to do it.

I'm using TestNG too, I know that makes a difference in what's allowable and what's not.

Thank you!

回答1:

Use findElements which will return a list of 0 if the element does not exist.

E.G:

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.


回答2:

You can use wait with try/catch to get all buttons and click on each if exist.

1.If alerts all appear at once use code below:

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.If alerts appear singly use code below:

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){ }