我最近开始学习VBA,并且在抓取数据方面遇到了一些困难。我想通过Expedia检索从新加坡到曼谷的每日最低票价。
我目前的代码只能检索引用网站源代码中“formattedTotalPrice”的第一行代码,这可能不是最低价格,所有单词价格都是相同的。如果有人可以帮助新手,我将非常感激!
Sub GetPrices()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")
Dim pth As String
pth = "https://www.expedia.com.sg/Flights-Search?rfrr=TG.LP.SrchWzd.Flight&langid=2057&trip=OneWay&leg1=from:Singapore,%20Singapore%20(SIN-Changi),to:Bangkok,%20Thailand%20(BKK-Suvarnabhumi%20Intl.),departure:" & DateAdd("d", 1, Date) & "TANYT&passengers=children:0,adults:1,seniors:0,infantinlap:Y&options=cabinclass:economy,sortby:price,carrier:&mode=search&paandi=true"
Dim lastRow As Integer
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
Set XMLHTTP = CreateObject("MSXML2.serverXMLHTTP")
XMLHTTP.Open "GET", pth, False
XMLHTTP.setRequestHeader "Content-Type", "text/xml"
XMLHTTP.send
buf = XMLHTTP.ResponseText
Locn_price = InStr(1, buf, "formattedTotalPrice\")
Locn_end = InStr(Locn_price, buf, "totalPriceAsDecimal\")
trim_price = Mid(buf, Locn_price + 27, Locn_end - 32 - Locn_price)
ws.Cells(lastRow + 1, 1).Value = Date
ws.Cells(lastRow + 1, 2).Value = trim_price
End Sub