使用Selenium库进行动态网站VBA爬虫时无法关闭弹窗的问题
问题分析
爬取West Elm动态加载页面时无法关闭弹窗并报错,核心原因是元素未完全加载就尝试定位,或定位选择器与实际页面结构不匹配。你需要提取产品名称、新旧价格及图片URL,需在弹窗处理完成后进行数据抓取。
解决方案
1. 引入显式等待
使用WebDriverWait等待元素可交互,避免因页面未加载完成导致的元素找不到错误。
2. 修正弹窗定位选择器
匹配页面实际DOM结构,调整选择器确保准确定位关闭按钮。
3. 完整爬取流程
关闭弹窗后遍历产品列表,提取目标数据并写入Excel。
修改后的代码
Option Explicit Private cd As Selenium.ChromeDriver Private wait As Selenium.WebDriverWait Sub ScrapeWestElmProducts() Set cd = New Selenium.ChromeDriver Set wait = New Selenium.WebDriverWait(cd, 10) '设置10秒等待超时 '启动浏览器并打开目标页面 cd.Start cd.Get "https://www.westelm.com/shop/furniture/all-living-room/?cm_type=gnav&originsc=furniture" On Error Resume Next '处理可能不存在的弹窗 '等待并关闭初始遮罩弹窗 wait.Until(Function(d) d.FindElementByClass("dismiss-overlay-text").IsDisplayed) cd.FindElementByClass("dismiss-overlay-text").Click '等待并关闭"No thanks"弹窗 wait.Until(Function(d) d.FindElementByXPath("//a[contains(@class,'not-into-savings')]").IsDisplayed) cd.FindElementByXPath("//a[contains(@class,'not-into-savings')]").Click On Error GoTo 0 '等待产品列表加载完成 wait.Until(Function(d) d.FindElementByClass("product-grid").IsDisplayed) Dim products As Selenium.WebElements Dim product As Selenium.WebElement Dim rowNum As Integer rowNum = 2 '从Excel第2行开始写入数据 '写入表头 Cells(1, 1) = "产品名称" Cells(1, 2) = "原价" Cells(1, 3) = "现价" Cells(1, 4) = "图片URL" Set products = cd.FindElementsByClass("product-card") '遍历产品提取数据 For Each product In products '提取产品名称 Cells(rowNum, 1) = product.FindElementByClass("product-title").Text '提取价格(处理单/双价格显示情况) Dim priceElements As Selenium.WebElements Set priceElements = product.FindElementsByClass("price") If priceElements.Count >= 2 Then Cells(rowNum, 2) = priceElements(0).Text '原价 Cells(rowNum, 3) = priceElements(1).Text '现价 Else Cells(rowNum, 3) = priceElements(0).Text '仅显示一个价格时设为现价 End If '提取图片URL Cells(rowNum, 4) = product.FindElementByTag("img").Attribute("src") rowNum = rowNum + 1 Next product '关闭浏览器并释放资源 cd.Quit Set cd = Nothing Set wait = Nothing MsgBox "数据抓取完成!" End Sub
关键说明
- 显式等待:通过
WebDriverWait确保元素加载完成后再操作,避免NoSuchElementException报错。 - 容错处理:用
On Error Resume Next处理弹窗可能不存在的情况,防止程序崩溃。 - 数据提取:针对产品卡片结构,分别定位名称、价格、图片元素,兼容单/双价格的显示场景。
内容的提问来源于stack exchange,提问作者Nooh_Noah
相关产品推荐
相关产品推荐

