VBA爬取Steam价格遇IE故障,求其他浏览器Web Scraping方案
替代IE的Steam价格爬取方案
首先得说,Steam早就停止对IE的优化支持了,你遇到的菜单加载失败、交互无效都是正常现象——毕竟IE已经被微软放弃,现代网站基本都不再适配它了。不用纠结IE的问题,下面给你两个实用的替代方案,都是基于Chrome/Edge这类现代浏览器的,上手难度也不高。
方案一:用Selenium Basic配合Chrome/Edge
Selenium是专门做网页自动化的工具,支持所有主流浏览器,操作逻辑和你原来的IE代码很像,适合新手过渡。
准备步骤:
- 安装Selenium Basic:去官方下载对应你系统的版本,安装完成后打开VBA编辑器,在「工具」→「引用」里勾选「Selenium Type Library」
- 下载对应浏览器的Driver:比如Chrome的ChromeDriver,要和你当前Chrome版本匹配,把Driver放到系统路径或者VBA文件同目录下
修改后的代码示例:
Sub SPrice_Selenium() Dim driver As New ChromeDriver '如果用Edge就换成EdgeDriver Dim itemEle As WebElement Dim y As Integer Dim x As Integer driver.Start "chrome" '启动Chrome,Edge的话写"edge" driver.Window.Maximize '可选,最大化窗口 y = 1 For x = 1 To 21 driver.Get "http://steamcommunity.com/market/search?appid=578080#p" & x & "x_name_asc" driver.Wait 2 '等待页面加载,也可以用更精准的等待方式,比如等待元素出现 '遍历商品链接元素 For Each itemEle In driver.FindElementsByClass("market_listing_row_link") '获取价格文本 Dim priceEle As WebElement On Error Resume Next '防止个别商品价格加载失败报错 Set priceEle = itemEle.FindElementByClass("market_listing_right_cell market_listing_their_price").FindElementByTag("span", 2) If Not priceEle Is Nothing Then Sheets("Sheet1").Range("E" & y).Value = priceEle.Text y = y + 1 End If On Error GoTo 0 Next Next x driver.Quit '关闭浏览器 End Sub
代码说明:
- 用
ChromeDriver代替原来的InternetExplorer,操作逻辑和IE类似,但支持现代浏览器 Wait方法用来等待页面加载,比原来的Busy判断更可靠- 加入了错误处理,避免个别商品加载异常导致程序中断
方案二:用XMLHTTP直接请求页面(轻量无浏览器)
如果不想安装额外工具,可以用VBA自带的XMLHTTP直接获取网页源码,再解析价格。这种方式更轻量,但需要注意Steam的反爬机制。
代码示例:
Sub SPrice_XMLHTTP() Dim xhr As Object Dim htmlDoc As HTMLDocument Dim itemEle As Object Dim y As Integer Dim x As Integer Dim url As String Set xhr = CreateObject("MSXML2.XMLHTTP.6.0") Set htmlDoc = New HTMLDocument y = 1 For x = 1 To 21 url = "http://steamcommunity.com/market/search?appid=578080#p" & x & "x_name_asc" '发送请求,模拟浏览器头 xhr.Open "GET", url, False xhr.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" xhr.send '加载源码到HTML文档 htmlDoc.body.innerHTML = xhr.responseText '遍历商品元素 For Each itemEle In htmlDoc.getElementsByClassName("market_listing_row_link") On Error Resume Next Dim priceText As String priceText = itemEle.getElementsByClassName("market_listing_right_cell market_listing_their_price")(0).getElementsByTagName("span")(1).textContent If priceText <> "" Then Sheets("Sheet1").Range("E" & y).Value = priceText y = y + 1 End If On Error GoTo 0 Next Next x Set xhr = Nothing Set htmlDoc = Nothing End Sub
注意事项:
- 必须设置
User-Agent请求头,伪装成现代浏览器,否则Steam会拒绝请求 - 如果遇到请求被拦截,可以尝试添加
Cookie头(先在浏览器里登录Steam,复制cookie过来) - 这种方式没有浏览器渲染,部分动态加载的内容可能获取不到,如果遇到这种情况,还是推荐用Selenium方案
额外提示
- Steam的市场页面有反爬机制,不要太快请求,建议在循环里加
Application.Wait Now + TimeValue("00:00:02")来控制请求间隔,避免被封IP - 如果需要登录后才能访问的内容,Selenium可以直接模拟登录,比XMLHTTP更方便
内容的提问来源于stack exchange,提问作者Ömer Faruk iskender
相关产品推荐
相关产品推荐

