wait.until(ExpectedConditions.visibilityOf Element1 OR Element2)

后端 未结 8 1121
遇见更好的自我
遇见更好的自我 2020-12-14 12:30

I want use wait.until(ExpectedConditions) with TWO elements. I am running a test, and I need WebDriver to wait until either of Element1 OR

相关标签:
8条回答
  • 2020-12-14 13:05

    I think that your problem has a simple solution if you put "OR" into xpath.

    WebDriverWait wait = new WebDriverWait(driver, 60); 
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h2[@class='....'] | //h3[@class='... ']"))); 
    

    Then, to print the result use for example:

    if(driver.findElements(By.xpath("//h2[@class='....']")).size()>0){
           driver.findElement(By.xpath("//h2[@class='....']")).getText();
    }else{
           driver.findElement(By.xpath("//h3[@class='....']")).getText();
    }
    
    0 讨论(0)
  • 2020-12-14 13:14

    This is the method I declared in my Helper class, it works like a charm. Just create your own ExpectedCondition and make it return any of elements found by locators:

    public static ExpectedCondition<WebElement> oneOfElementsLocatedVisible(By... args)
    {
        final List<By> byes = Arrays.asList(args);
        return new ExpectedCondition<WebElement>()
        {
            @Override
            public Boolean apply(WebDriver driver)
            {
                for (By by : byes)
                {
                    WebElement el;
                    try {el = driver.findElement(by);} catch (Exception r) {continue;}
                    if (el.isDisplayed()) return el;
                }
                return false;
            }
        };
    }
    

    And then you can use it this way:

    Wait wait = new WebDriverWait(driver, Timeouts.WAIT_FOR_PAGE_TO_LOAD_TIMEOUT);
    WebElement webElement = (WebElement) wait.until(
            Helper.oneOfElementsLocatedVisible(
                    By.xpath(SERVICE_TITLE_LOCATOR), 
                    By.xpath(ATTENTION_REQUEST_ALREADY_PRESENTS_WINDOW_LOCATOR)
            )
    );
    

    Here SERVICE_TITLE_LOCATOR and ATTENTION_REQUEST_ALREADY_PRESENTS_WINDOW_LOCATOR are two static locators for page.

    0 讨论(0)
提交回复
热议问题