首页 > 解决方案 > 使用 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>&nbsp;<span _ngcontent-app-root-c122="" class="wu-label"><span _ngcontent-app-root-c122="" class="ng-star-inserted">%</span>

目前,只需了解如何从表中获取云覆盖百分比就足够了。任何人都可以帮忙吗?非常感谢!

标签: excelvbaweb-scraping

解决方案


我没有阅读您的整个问题,但我猜您想要这样的东西(这是与基于 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

结果:

在此处输入图像描述


推荐阅读