如何使用VBA从网站上抓取数据?

时间:2017-10-25 15:05:10

标签: vba excel-vba extract excel

我是VBA的新手,并试图从Expedia(SG到曼谷)提取航班价格。不幸的是,我的代码运行得不好。它只返回一个价格(我不知道它来自哪里)。如果有人能帮助我,真的很感激。谢谢!

Sub ExtractRaw() 
Dim wb As Workbook 
Dim ws As Worksheet 
Set wb = ThisWorkbook 
Set ws = wb.Sheets("Sheet1") 

Dim ie As Object 
Set ie = CreateObject("InternetExplorer.Application") 
With ie 
.Visible = True .navigate "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" 

Do While ie.Busy 
DoEvents 
Loop 

Dim doc As HTMLDocument 
Set doc = ie.document 
While ie.readyState <> 4 
Wend 
On Error Resume Next 

Dim i As Integer For i = 0 To 200 
Range("A1").Value = ie.document.getElementById("flight-listing-container").getElementsByClassName("dollars price-emphasis")(i).innerText 

Next i 
ie.Quit 
Application.EnableEvents = True 
End With 
End Sub

1 个答案:

答案 0 :(得分:1)

我认为你的问题在这里:

Dim i As Integer 
    For i = 0 To 200 
    Range("A1").Value = ie.document.getElementById("flight-listing-container").getElementsByClassName("dollars price-emphasis")(i).innerText 
Next i 

您循环任意200次,然后以价格重复更新单元格A1。这意味着您将始终留下在A1

中匹配的最后一个元素的内部文本

尝试

Range("A1").Offset(i,0).Value = ie.document.getElementById("flight-listing-container").getElementsByClassName("dollars price-emphasis")(i).innerText

这将给你一个列表,列出它在A列上找到的所有内部文本,直到你的循环结束。

真的,我认为你应该确定在进入循环之前你需要循环多少次迭代,除非你有充分的理由每次循环200次。