如何用VBA+Selenium实现动态生成网页的滚动加载?
解决Selenium动态懒加载页面滚动加载问题的可行方案
针对你遇到的动态页面需滚动才加载内容、常规滚动脚本无效的问题,提供以下几个替代缩放的方案:
方案1:定位实际滚动容器进行滚动
很多现代网站会使用嵌套的自定义滚动容器(如带overflow: scroll属性的div)而非页面body作为滚动区域,这会导致window.scrollTo针对body的操作无效。你需要先定位到这个容器,再对其执行滚动操作:
Sub ScrollContainer(ch As Selenium.ChromeDriver) Dim scrollContainer As WebElement ' 替换为实际滚动容器的定位方式(XPath/Class等) Set scrollContainer = ch.FindElementByXPath("//div[contains(@class, 'your-scroll-container-class')]") Dim lastHeight As Long lastHeight = ch.ExecuteScript("return arguments[0].scrollHeight", scrollContainer) Do While True ' 滚动到容器底部 ch.ExecuteScript("arguments[0].scrollTop = arguments[0].scrollHeight", scrollContainer) ' 等待内容加载 Application.Wait Now + TimeValue("0:00:02") Dim newHeight As Long newHeight = ch.ExecuteScript("return arguments[0].scrollHeight", scrollContainer) ' 高度不变说明已加载完所有内容 If newHeight = lastHeight Then Exit Do End If lastHeight = newHeight Loop End Sub
方案2:模拟逐步滚动(接近手动滚动行为)
一次性滚动到底部可能被网站的懒加载逻辑忽略,改用scrollBy逐步滚动更符合用户操作习惯,更容易触发加载:
Sub StepScroll(ch As Selenium.ChromeDriver) Dim i As Integer ' 调整循环次数以覆盖页面内容 For i = 1 To 25 ' 每次向下滚动400像素 ch.ExecuteScript("window.scrollBy(0, 400);") ' 等待内容加载(可根据页面加载速度调整时间) Application.Wait Now + TimeValue("0:00:01") Next i ' 最后滚动到页面底部确保所有内容加载完成 ch.ExecuteScript("window.scrollTo(0, document.documentElement.scrollHeight);") Application.Wait Now + TimeValue("0:00:02") End Sub
方案3:结合元素查找循环滚动
以目标元素css-w166kv-LegendLabel-LegendClickable为锚点,循环滚动并尝试查找元素,直到加载到目标数量或页面底部:
Sub ScrollUntilElementsLoaded(ch As Selenium.ChromeDriver, targetCount As Integer) Dim targetElements As WebElements On Error Resume Next Do ' 每次滚动500像素 ch.ExecuteScript("window.scrollBy(0, 500);") Application.Wait Now + TimeValue("0:00:01") ' 查找目标元素 Set targetElements = ch.FindElementsByClass("css-w166kv-LegendLabel-LegendClickable") ' 检查是否到达页面底部 Dim currentScrollPos As Long currentScrollPos = ch.ExecuteScript("return window.pageYOffset || document.documentElement.scrollTop") Dim pageHeight As Long pageHeight = ch.ExecuteScript("return document.documentElement.scrollHeight") ' 滚动位置接近底部或已找到足够元素时退出循环 If (currentScrollPos + ch.WindowSize.Height >= pageHeight) Or (targetElements.Count >= targetCount) Then Exit Do End If Loop On Error GoTo 0 End Sub
补充说明
你之前的滚动脚本无效,大概率是因为:
- 页面的滚动容器不是
document.body,而是内部嵌套的div,导致针对body的滚动操作无法触发内容加载; - 一次性滚动到底部的行为不符合网站懒加载的触发逻辑,逐步滚动更易被识别为用户操作。
内容的提问来源于stack exchange,提问作者MonroeGA
相关产品推荐
相关产品推荐

