【问题标题】:Selenium WebDriverWait doesn't return all web elements within classes with same nameSelenium WebDriverWait 不会返回具有相同名称的类中的所有 Web 元素
【发布时间】:2022-08-18 04:40:34
【问题描述】:

我使用这种方法从div 类中检索所有src。例如,在我的代码页面中有 5 个元素,但是当我运行此代码时,我只得到 2 个src。如果我多次运行我的代码,有时它会返回所有 5 个元素。

public static void main(String[] args) throws IOException, URISyntaxException {
        System.setProperty(\"webdriver.chrome.driver\", \"S:\\\\behance-id\\\\src\\\\main\\\\resources\\\\chromedriver.exe\");
        WebDriver driver = new ChromeDriver();
        driver.get(\"https://www.behance.net/gallery/148589707/Hercules-and-Randy\");
        List<WebElement> firstResult = new WebDriverWait(driver, Duration.ofSeconds(10))
                .until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(\"//div[@class=\'ImageElement-root-kir ImageElement-loaded-icR\']/img\")));
        for (WebElement webElement : firstResult) {
            System.out.println(webElement.getAttribute(\"src\"));
        }
        driver.quit();
    }

还尝试添加此行,但没有帮助:

((JavascriptExecutor)driver).executeScript(\"window.scrollTo(0, document.body.scrollHeight)\");

所以这个脚本不会返回所有需要的元素,即使它们是同一个类。

页面源代码如下:

  • 在您尝试获取元素时,元素可能尚未加载。尝试等待几秒钟
  • 我将超时时间增加到 30 秒 - 它没有帮助。在这种情况下超时无效

标签: java selenium


【解决方案1】:
ExpectedCondition<java.util.List<WebElement>> presenceOfAllElementsLocatedBy(By locator)

以上用于检查网页上是否存在至少一个元素,一旦找到就会中断,它不会等待 5 个元素。一旦 elements.size>0 就返回 true

您需要添加一些其他等待以确保在执行 findelements 之前已加载所有元素

下面将等待元素计数为 5

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver driver) {
                int elementCount = driver.findElements(By.xpath("xxxx")).size();
                if (elementCount == 5)
                    return true;
                else
                    return false;
            }
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多