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

时间:2017-12-20 23:52:51

标签: vba excel-vba excel

代码大师!

新手在这里!我试图创建一个工具,使用.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属性中获取文字。任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

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

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

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

Debug.Print EmployeeID.innerText