我想在 Excel 中获取 AliExpress 商品的价格。
我发现这获取产品名称和价格。代码如下:
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
' If website = "" 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, Price1, Price2, Price3, URL
但每当我运行这个宏时,我都会收到一条错误
name = html.getElementsByClassName("title--wrap--Ms9Zv4A").Item(0).innerText
错误说:
Run-time error '91':
Object variable or With block variable not set
编辑:
我放回复放入单元格,然后将其复制到笔记文档中,然后使用Ctrl+搜索F,但找不到它。我仔细查看了 html,发现第一部分文本与网站匹配(当我使用浏览器中的检查工具时),但其余部分不匹配,并且缺少很多字符。这是什么原因造成的?
编辑:
我在 C# WinForms 中重新创建了它,我发现生成的文件中的 html 比 VB.net 版本多得多。仔细检查 html 后发现,所有信息都在那里,只是格式不同。我不知道为什么,但我可以使用它。