You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium WebDriverWait无法稳定获取同名类下全部Web元素求助

Behance页面图片src提取不全问题解决

问题背景

需要从Behance指定页面中,提取所有<div class="ImageElement-root-kir ImageElement-loaded-icR">下img标签的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)");

页面情况

页面源码显示目标div容器下包含多个img元素,但部分图片因未进入视口或未完成加载,导致无法被抓取。


解决思路与修改后的代码

问题核心在于:单次滚动不足以触发所有图片懒加载,且presenceOfAllElementsLocatedBy仅判断元素存在于DOM,不保证元素可见或资源加载完成。以下是修复方案:

public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException {
    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");
    JavascriptExecutor js = (JavascriptExecutor) driver;
    
    // 循环滚动直到页面停止加载,确保所有图片进入视口
    long lastScrollHeight = (long) js.executeScript("return document.body.scrollHeight");
    while (true) {
        js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
        Thread.sleep(2000); // 等待内容加载
        long newScrollHeight = (long) js.executeScript("return document.body.scrollHeight");
        if (newScrollHeight == lastScrollHeight) {
            break;
        }
        lastScrollHeight = newScrollHeight;
    }
    
    // 等待所有目标图片元素可见(而非仅存在)
    List<WebElement> imageElements = new WebDriverWait(driver, Duration.ofSeconds(15))
            .until(ExpectedConditions.visibilityOfAllElementsLocatedBy(
                    By.xpath("//div[contains(@class, 'ImageElement-root') and contains(@class, 'ImageElement-loaded')]/img")));
    
    // 遍历每个图片,确保资源加载完成后再获取src
    for (WebElement img : imageElements) {
        // 检查图片是否已加载完成(naturalWidth>0表示图片资源已加载)
        new WebDriverWait(driver, Duration.ofSeconds(5)).until(driver -> 
                (boolean) js.executeScript("return arguments[0].naturalWidth > 0", img));
        System.out.println(img.getAttribute("src"));
    }
    
    driver.quit();
}

关键修改点

  1. 循环滚动加载:持续滚动直到页面高度不再变化,确保所有图片进入视口触发懒加载
  2. 等待元素可见:用visibilityOfAllElementsLocatedBy替代presenceOfAllElementsLocatedBy,确保元素已渲染可见
  3. 动态类名匹配:xpath改用contains匹配类名前缀,避免Behance动态生成的哈希后缀(如-kir、-icR)导致定位失败
  4. 图片加载验证:通过naturalWidth属性确认图片资源已完全加载,避免获取到未加载的占位src

内容的提问来源于stack exchange,提问作者fujidaon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 17:55:47