I very recently started learning VBA and is facing some difficulties in scraping data. I would like to retrieve the daily minimum flight price from Singapore to Bangkok.
My current code is only able to retrieve the first line of code referencing to "formattedTotalPrice" in the website source code, which might not be the minimum price. Would be really grateful if someone could help a newbie out!
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:" & 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)
Debug.Print trim_price
ws.Cells(lastRow + 1, 1).Value = Date
ws.Cells(lastRow + 1, 2).Value = trim_price
End Sub
The Date need to be formatted DD/MM/YYYY: Format(Date, "dd/mm/yyyy")