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(); }
关键修改点
- 循环滚动加载:持续滚动直到页面高度不再变化,确保所有图片进入视口触发懒加载
- 等待元素可见:用
visibilityOfAllElementsLocatedBy替代presenceOfAllElementsLocatedBy,确保元素已渲染可见 - 动态类名匹配:xpath改用
contains匹配类名前缀,避免Behance动态生成的哈希后缀(如-kir、-icR)导致定位失败 - 图片加载验证:通过
naturalWidth属性确认图片资源已完全加载,避免获取到未加载的占位src
内容的提问来源于stack exchange,提问作者fujidaon
相关产品推荐
相关产品推荐

