Excel VBA获取速卖通商品实时数据报错及HTML内容异常问题求助
Excel VBA获取速卖通商品实时数据报错及HTML内容异常问题求助
大家好,我现在想通过Excel VBA获取速卖通商品的名称和价格信息,已经写了一段宏代码,但运行时遇到了问题,想请教各位帮忙看看。
我的需求是:从指定的速卖通商品链接(存放在Excel的URL命名单元格里)获取商品名称和不同规格的价格,然后把结果写入Name、Price1、Price2、Price3这些命名单元格中。
下面是我编写的VBA代码:
Sub hello() Dim request As Object Dim response As String Dim html As New HTMLDocument Dim website As String Dim name As String Dim price1, price2, price3 As Long ' Website to go to. website = Range("URL").Value If InStr(website, "https://") <= 0 Then Exit Sub End If ' Create the object that will make the webpage request. Set request = CreateObject("MSXML2.XMLHTTP") ' Where to go and how to go there - probably don't need to change this. request.Open "GET", website, False ' Get fresh data. request.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" ' Send the request for the webpage. request.send ' Get the webpage response data into a variable. response = StrConv(request.responseBody, vbUnicode) ' Put the webpage into an html object to make data references easier. html.body.innerHTML = response ' Get the price from the specified element on the page. name = html.getElementsByClassName("title--wrap--Ms9Zv4A").Item(0).innerText price1 = html.getElementsByClassName("es--wrap--erdmPRe").Item(0).innerText price2 = html.getElementsByClassName("es--wrap--erdmPRe").Item(1).innerText price3 = html.getElementsByClassName("es--wrap--erdmPRe").Item(2).innerText ' Output the price into a message box. ' MsgBox price Range("Name").Value = name Range("Price1").Value = price1 * 1 Range("Price2").Value = price2 * 1 Range("Price3").Value = price3 * 1 End Sub
遇到的问题
每次运行这个宏,都会在这一行抛出错误:
name = html.getElementsByClassName("title--wrap--Ms9Zv4A").Item(0).innerText
错误提示为:
Run-time error '91': Object variable or With block variable not set
排查过程
我把response的内容输出到Excel单元格中,再复制到记事本里搜索title--wrap--Ms9Zv4A这个类名,结果完全找不到。对比浏览器开发者工具里看到的网页HTML,发现VBA获取到的内容只有开头部分和网页匹配,后面大量内容缺失,字符也有异常。
后来我用C# WinForms重新实现了类似的逻辑,生成的HTML文件里内容完整很多,仔细查看后发现商品的名称和价格信息其实都存在,只是格式和VBA里获取到的不一样。但我搞不懂为什么VBA中获取的HTML会出现这种情况,也不知道该怎么修改代码来正确提取数据。
有没有大佬能帮我分析下问题根源,以及给出修改VBA代码的解决方案呀?
备注:内容来源于stack exchange,提问作者John Doe
相关产品推荐
相关产品推荐

