excel - 使用 VBA 从天气网站提取数据
问题描述
我正在尝试从https://www.wunderground.com上的天气预报表中复制特定数据。更准确地说,我正在尝试从https://www.wunderground.com/hourly/ro/mizil之类的链接以表格格式(但现在任何格式都可以)获取 Excel 中的时间和云层/45.00,26.44/date/2020-04-15。到目前为止,我已经尝试了很多方法来获取特定的数据,但我还不够(我是使用 VBA 进行网络抓取的新手)。这些概念和命令对我来说很清楚,并且它们已在其他站点上工作过,但是对于这个站点,我束手无策。目前,我正在使用:
Sub WeatherScrap()
Range("A1").Select
Dim mainlink As String Dim http As New XMLHTTP60, html As New HTMLDocument Dim CloudCover As Object
mainlink = "https://www.wunderground.com/hourly/ro/mizil/45.00,26.44/date/2020-04-15"
With http
.Open "GET", mainlink, False
.send
html.body.innerHTML = .responseText
End With
For Each CloudCover In html.getElementsByClassName("wu-value wu-value-to")
ActiveCell.Value = CloudCover.innerText
ActiveCell.Offset(1, 0).Select
Next CloudCover
End Sub
我显然没有在 html 上引用正确的类、标签或 ID(到目前为止我已经尝试了很多,但没有一个检索到所需的数据)。网站上的 html 元素是:
<lib-display-unit _ngcontent-app-root-c213="" _nghost-app-root-c122="" class="ng-star-inserted"><span _ngcontent-app-root-c122="" class="test- wu-unit wu-unit-chance ng-star-inserted"><!----><!----><!----><span _ngcontent-app-root-c122="" class="wu-value wu-value-to">100</span> <span _ngcontent-app-root-c122="" class="wu-label"><span _ngcontent-app-root-c122="" class="ng-star-inserted">%</span>
目前,只需了解如何从表中获取云覆盖百分比就足够了。任何人都可以帮忙吗?非常感谢!
解决方案
我没有阅读您的整个问题,但我猜您想要这样的东西(这是与基于 Web 的表格交互的一种非常常见的方式)。
Sub Web_Table()
Dim HTMLDoc As New HTMLDocument
Dim objTable As Object
Dim lRow As Long
Dim lngTable As Long
Dim lngRow As Long
Dim lngCol As Long
Dim ActRw As Long
Dim objIE As InternetExplorer
Set objIE = New InternetExplorer
objIE.Navigate "https://www.wunderground.com/hourly/ro/mizil/45.00,26.44/date/2020-04-15"
Do Until objIE.ReadyState = 4 And Not objIE.Busy
DoEvents
Loop
Application.Wait (Now + TimeValue("0:00:03")) 'wait for java script to load
HTMLDoc.body.innerHTML = objIE.Document.body.innerHTML
With HTMLDoc.body
Set objTable = .getElementsByTagName("table")
For lngTable = 0 To objTable.Length - 1
For lngRow = 0 To objTable(lngTable).Rows.Length - 1
For lngCol = 0 To objTable(lngTable).Rows(lngRow).Cells.Length - 1
ThisWorkbook.Sheets("Sheet1").Cells(ActRw + lngRow + 1, lngCol + 1) = objTable(lngTable).Rows(lngRow).Cells(lngCol).innerText
Next lngCol
Next lngRow
ActRw = ActRw + objTable(lngTable).Rows.Length + 1
Next lngTable
End With
objIE.Quit
End Sub
结果:
推荐阅读
- android - 如何在 Android/NDK 上将命令行参数从 gradlew.bat 传递到 Clang
- angular - 无法在 Firebase 和 Angular 中读取 null 的属性“uid”
- python - 创建一个读取文件,存储在数组中,然后打印单词出现在数组中的次数的函数
- javascript - 遇到未捕获的类型错误:无法读取未定义的属性
- css - 如何在保持按钮右对齐的同时折叠标题中的文本?
- python - 在 TSP 的距离公式中返回“不是数字”
- android - Google Play 中的测试订单会在五分钟后自动退款
- google-cloud-platform - 在 GCP VM 上训练深度学习模型时出现 ssh 超时错误
- python - Scipy 的 Odeint 在初始时间步解决方案后返回零
- c# - 我的 DataTemplate 未在 WPF 应用程序中显示来自 ObservableCollection 的数据
>