Excel VBA:导航到新页面时,网页HTML不显示

我试图在Excel中创build一个VBAmacros:

  1. 导航到网页
  2. 在HTML文档中search标签名称为“input”的所有元素
  3. 打印find的每个元素的属性(名称,types和值)
  4. 点击网页上的button导航到第二个网页。
  5. 在第二页的HTML文档中search标签名称为“input”的所有元素
  6. 打印find的每个元素的属性(名称,types和值)

一切工作,直到第5步find。当我尝试searchHTML文档时,出于某种原因,它不search第二页的HTML文档,而是查看第2步中的初始网页的HTML,并打印出步骤3中的结果相同。

请你们看看我的代码,看看我做错了什么? 我在下面列出了我的代码,并试图发表评论,使其可读性。

Sub C_R() Dim ie As New SHDocVw.InternetExplorer Dim HTMLDoc As MSHTML.HTMLDocument Dim HTMLInput As MSHTML.IHTMLElement Dim HTMLButtons As MSHTML.IHTMLElementCollection Dim HTMLButton As MSHTML.IHTMLElement 'Opens Internet Explorer and navigates to website. ie.Visible = True ie.navigate "http://openaccess.sb-court.org/OpenAccess/" Do While ie.ReadyState <> READYSTATE_COMPLETE Loop 'Searches HTML(initial page) to find all elements with "input" tag name. 'Prints attributes of each element (name, type, and value". Set HTMLDoc = ie.Document Set HTMLButtons = HTMLDoc.getElementsByTagName("input") Debug.Print "Initial Page" For Each HTMLButton In HTMLButtons Debug.Print HTMLButton.getAttribute("name"), HTMLButton.getAttribute("type"), HTMLButton.getAttribute("value") Next HTMLButton 'Navigates to second page HTMLButtons(1).Click Do While ie.ReadyState <> READYSTATE_COMPLETE Loop 'Searches HTML(second page) to find all elements with "input" tag name. 'Prints attributes of each element (name, type, and value". Set HTMLDoc = ie.Document Set HTMLButtons = HTMLDoc.getElementsByTagName("input") Debug.Print "Second Page" For Each HTMLButton In HTMLButtons Debug.Print HTMLButton.getAttribute("name"), HTMLButton.getAttribute("type"), HTMLButton.getAttribute("value") Next HTMLButton End Sub 

任何帮助,您可以提供将不胜感激。 非常感谢。

看起来你的第二个循环正在继续,即使网页还没有完全加载。

  Do While ie.ReadyState <> READYSTATE_COMPLETE Loop 

要看到这一点,在第二个循环放置一个断点,并等待加载第二个网页。 然后继续代码,它应该工作正常。

您将需要在循环中添加一个等待时间,这可能并不总是工作,或者find另一种方法来判断ie.ReadyState是否完成。