首页 > 解决方案 > VBA 无法获取元素和输入数据

问题描述

这是我希望输入数据的网站:网站在“来自城市/机场”下

我为该输入框找到了以下 HTML 元素:

<input name="frm1" class="frm1 col-sm-12 ui-autocomplete-input" autocomplete="off">

下面是我的 VBA 代码:

Sub Data_Scrap()

    Dim IE As SHDocVw.InternetExplorer, HTMLDoc As MSHTML.HTMLDocument, HTMLInput As MSHTML.IHTMLElementCollection, x As MSHTML.IHTMLElement
    Set IE = New SHDocVw.InternetExplorer

    IE.Visible = True
    IE.navigate "https://www.icao.int/environmental-protection/Carbonoffset/Pages/default.aspx"

    'Wait until the website is loaded
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)
    Loop

    Set HTMLDoc = IE.document

    Set HTMLInput = HTMLDoc.getElementsByTagName("input")

    For Each x In HTMLInput
        If x.getAttribute("name") = "frm1" Then
            x.innerText = "hkg"
            Exit For
        End If
    Next
End Sub

我也尝试了一些更简单的方法,HTMLDoc.getElementsByTagName("frm1")(0).value = "hkg"但它出现了错误:

未设置对象变量或 With 块变量

标签: excelvbaweb-scraping

解决方案


推荐阅读