Java Selenium - 如何在流中添加等待元素?

问题描述 投票:0回答:1

你能告诉我如何在网络元素流中为网络元素添加明确的等待时间吗?

driver.findElements(By.xpath("thisIsXpath"))
.stream()
.map(WebElement::getText)
.map(String::trim)
.collect(Collectors.toList());
java selenium-webdriver stream
1个回答
0
投票

要在使用 Java Selenium 时添加等待流中的元素,您可以使用 WebDriverWait 类和 ExpectedConditions。您应该首先创建一个 WebDriverWait 实例,然后使用自定义 lambda 函数等待流中的元素。这是如何执行此操作的示例:

import java.util.List;
import java.util.stream.Collectors;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SeleniumExample {

    public static void main(String[] args) {
        WebDriver driver = // Initialize your WebDriver instance here
        WebDriverWait wait = new WebDriverWait(driver, 10); // 10 seconds is the timeout

        List<String> elementTexts = driver.findElements(By.xpath("thisIsXpath"))
                .stream()
                .peek(element -> wait.until(ExpectedConditions.visibilityOf(element)))
                .map(WebElement::getText)
                .map(String::trim)
                .collect(Collectors.toList());
        
        // Perform any necessary actions with the collected element texts
    }
}

在这个例子中,我们使用流上的peek()方法来引入等待步骤。 peek() 中的 lambda 函数等待每个元素可见,然后再继续流中的下一步。 WebDriverWait 实例初始化为 10 秒超时,这意味着它将等待最多 10 秒以使每个元素变得可见。您可以根据需要调整此超时值。

© www.soinside.com 2019 - 2024. All rights reserved.