【发布时间】:2020-02-24 09:39:08
【问题描述】:
我正在尝试从汽车租赁网站主页上抓取取货分行的位置。我们的想法是准确查看给定公司的取货分支机构的位置。
我之前已经成功创建过这个,但是这家公司最近修改了他们的网站,现在我的代码不起作用。分支位置似乎隐藏在某种形式中,只有在您单击取货位置空间后,这些位置才会在 html 中可见。
我当前的代码如下所示:
Option Explicit
Private Sub pickuplocations()
Dim html As Object
Dim ws As Worksheet
Dim headers()
Dim i As Long
Dim r As Long
Dim c As Long
Dim numrows As Long
Set ws = ThisWorkbook.Worksheets("Europcar Branches(2)")
Set html = New HTMLDocument
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://www.europcar.co.za", False
.send
html.body.innerHTML = .responseText 'fetches all html from the website
Dim pickupbranches As Object
Dim pickupbranchresults()
Set pickupbranches = html.getElementById("_location-search-widget_15").getElementsByTagName("span")
headers = Array("Pickup Location", "Option value") 'for the ws
numrows = pickupbranches.Length - 1 'sets the row length
ReDim pickupbranchresults(1 To numrows, 1 To 2) 'sets array size for the results
For i = 1 To numrows
pickupbranchresults(i, 1) = pickupbranches.Item(i).innerText
pickupbranchresults(i, 2) = pickupbranches.Item(i).Value
Next
With ws
.Cells(1, 1).Resize(1, UBound(headers) + 1) = headers 'sets the column headers
.Cells(2, 1).Resize(UBound(pickupbranchresults, 1), UBound(pickupbranchresults, 2)) = pickupbranchresults
End With
End With
End Sub
【问题讨论】:
-
您有问题吗? “我的代码不起作用”不是问题。
-
改用这个europcar.co.za/rental-locations 似乎更合理。此网址是否包含您需要的所有信息?如果是这样,那么似乎很容易得到它。
-
您当前的代码不会产生任何结果,因为位置列表未包含在页面的源 HTML 中。当您点击搜索栏时,它会动态加载。
-
@StavrosJon 所以我需要让代码循环遍历每个“选项卡”以抓取位置名称。或者弄清楚如何点击搜索栏来让它们动态加载。
-
@Hev 如果此链接 europcar.co.za/rental-locations 包含您感兴趣的所有信息,那么您可以通过一个 GET 请求以 JSON 格式获取所有位置。无需单独遍历所有选项卡。如果这确实是你需要的,我可以发布一个答案让你开始。
标签: excel vba web-scraping