我试图用XML从网站上提取数据。请看下面的脚本:
脚本
Option Explicit
Private Sub btnRefresh_Click()
Dim req As New XMLHTTP
Dim resp As New DOMDocument
Dim weather As IXMLDOMNode
Dim ws As Worksheet: Set ws = ActiveSheet
Dim wshape As Shape
Dim thiscell As Range
Dim i As Integer
req.Open "GET", "http://api.worldweatheronline.com/premium/v1/weather.ashx?key=myConfidentialToken&q=Baku&format=xml&num_of_days=5"
req.send
resp.LoadXML req.responseText
For Each weather In resp.getElementsByTagName("weather")
i = i + 1
ws.Range("theDate").Cells(1, i).Value = weather.SelectNodes("date")(0).Text
ws.Range("highTemps").Cells(1, i).Value = weather.SelectNodes("maxtempC")(0).Text
ws.Range("lowTemps").Cells(1, i).Value = weather.SelectNodes("mintempC")(0).Text
Set thiscell = ws.Range("weatherPicture").Cells(1, i)
Set wshape = ws.Shapes.AddShape(msoShapeRectangle, thiscell.Left, thiscell.Top, thiscell.Width, thiscell.Height)
wshape.Fill.UserPicture weather.SelectNodes("weatherIconUrl").Item(0).Text
Next weather
End Sub
此脚本返回运行时错误91.它表示:"对象变量或With块变量未设置"。当我调试时,跑步停在前一行"下一个天气"声明。为什么这个脚本会返回这样的错误,而我已经设置了我的" wshape"变量?
答案 0 :(得分:1)
正如@JohnRC指出的那样,每个<hourly>
节点内都有一组<weather>
个节点,而每个<hourly>
节点又包含<weatherIconUrl>
个节点。您可以将响应XML保存到文件中,并使用任何在线XML树查看器来查看结构:
看看下面的示例,添加了一个嵌套循环以从每个<weatherIconUrl>
节点获取<hourly>
:
Option Explicit
Private Sub btnRefresh_Click()
Dim oReq As Object
Dim sResp As String
Dim oDoc As Object
Dim oData As Object
Dim cDays As Object
Dim oDay As Object
Dim cHours As Object
Dim oHour As Object
Set oReq = CreateObject("MSXML2.XMLHTTP")
oReq.Open "GET", "http://api.worldweatheronline.com/premium/v1/weather.ashx?key=e11be04676ad49038f9175720181600&q=saint-petersburg&format=xml&num_of_days=5", False
oReq.Send
sResp = oReq.ResponseText
Set oDoc = CreateObject("MSXML2.DOMDocument")
oDoc.LoadXML sResp
Set oData = oDoc.getElementsByTagName("data")(0)
Set cDays = oData.SelectNodes("weather")
For Each oDay In cDays
Debug.Print oDay.SelectNodes("date")(0).Text
Debug.Print oDay.SelectNodes("maxtempC")(0).Text
Debug.Print oDay.SelectNodes("mintempC")(0).Text
Set cHours = oDay.SelectNodes("hourly")
For Each oHour In cHours
Debug.Print vbTab & oHour.SelectNodes("time")(0).Text
Debug.Print vbTab & oHour.SelectNodes("tempC")(0).Text
Debug.Print vbTab & oHour.SelectNodes("weatherIconUrl")(0).Text
Next
Next
End Sub