如何通过引用其id来获取元素的innerText?

问题描述 投票:0回答:1

代码大师!

新手在这里!我试图创建一个工具,使用.innerText方法通过引用元素的ID来从网站上抓取文本,但是对于一些ID,我只获得空格和/或中断。

这是网页的源代码:

<div id="empName">
  <h2>Employee Name</h2>
  <div class="clear"></div>
  <span style="font-family:Arial; font-weight:bold">
    <div id="empID">Employee ID</div>
  </span>

这是我的VBA代码:

Option Explicit

Sub SampleCode()

Dim IE As New SHDocVw.InternetExplorer
Dim HTMLDoc As MSHTML.IHTMLDocument
Dim EmployeeName As MSHTML.IHTMLElement
Dim EmployeeID As MSHTML.IHTMLElement
Dim URL As String

URL = "www.example"

With IE
    .Visible = True
    .FullScreen = True
    .Navigate URL
End With

Do
Loop Until IE.ReadyState = READYSTATE_COMPLETE And IE.Busy <> True

Set HTMLDoc = IE.Document
Set EmployeeName = HTMLDoc.getElementById("empName")
Set EmployeeID = HTMLDoc.getElementById("empID")

Debug.Print EmployeeName.tagName, EmployeeName.innerText, EmployeeID.tagName, EmployeeID.innerText

IE.FullScreen = False
IE.Quit
Set IE = Nothing

End Sub

这是立即窗口显示的结果:

DIV           Employee Name           DIV           

我按照YouTube上的教程但我无法从“empID”id属性中获取文本。任何建议将不胜感激。

vba excel-vba excel
1个回答
0
投票

您可以尝试等待文本填写:

timeout = Now + #0:00:05#  ' to wait up to 5 seconds

While EmployeeID.innerText = "" And Now < timeout 
    DoEvents
Wend

Debug.Print EmployeeID.innerText
© www.soinside.com 2019 - 2024. All rights reserved.