VBA,doc.getElementsByClassName()工作在debugging模式不运行模式

我在vba中使用下面的代码,

Set results = Doc.getElementsByClassName("a-size-large a-color-price olpOfferPrice a-text-bold") If results.Length > 0 Then 

但debugging模式下的长度只有在运行模式下不能超过1,我查了网站给了上面提到的类,但是在逐行debugging模式下debugging模式下工作不稳定,在运行模式下不工作。

谢谢DJ

这听起来像你正在加载的文件,但它没有完成,然后再尝试检查文件。 当以debugging模式运行时,文档有时间完成加载。 强制VBA等待文档完全加载的最好方法是在同步模式下打开URL / Document。 您还需要检查文档请求是否返回了有效的HTTP状态码。

如果你的文档源是有效的XML / XHTML,那么你可以直接从XMLHttpRequest获得一个文档对象,但我假设你有普通的旧HTML。

您需要知道XMLHttpRequest将检索页面的HTML内容,但不会加载或运行任何支持的脚本/ css,因此,如果其中任何脚本生成dynamicHTML内容,则不会存在于HTML文件中。

 Sub Test() Const URL As String = "http://stackoverflow.com" Const CLASS_NAME As String = "row-fluid" 'The getElementsByClassName method is unavailable under some/all IE versions? 'It seems to need to be strongly typed as MSHTML.HTMLDocument 'You'll need to Add a reference to Microsoft HTML Object Libarary Dim oDoc As MSHTML.HTMLDocument Dim results As Object With CreateObject("MSXML2.XMLHttp") .Open "GET", "http://www.microsoft.com", False .send 'Check the response is valid If .Status = 200 Then Set oDoc = CreateObject("htmlfile") oDoc.body.innerHTML = .responseText Set results = oDoc.getElementsByClassName(CLASS_NAME) End If End With End Sub 

假设你的代码试图从网站获取数据,使用下面的方法来获取数据。 在执行IF条件之前,此代码将等待HTML数据被提取。 (参考: 本网站的代码片段 )

 'Replace the URL of the webpage that you want to download Web_URL = "http://websitename.com" 'Create HTMLFile Object Set HTML_Content = CreateObject("htmlfile") 'Get the WebPage Content to HTMLFile Object With CreateObject("msxml2.xmlhttp") .Open "GET", Web_URL, False .send HTML_Content.Body.Innerhtml = .responseText End With 

通过检查IE的ReadyStateBusy属性来确保在尝试访问DOM元素之前加载页面:

 Sub Foo() Const READYSTATE_COMPLETE As Integer = 4 Set IE = CreateObject("InternetExplorer.Application") IE.Navigate "http://www.stackoverflow.com" '// The important bit: While IE.ReadyState <> READYSTATE_COMPLETE Or IE.Busy DoEvents Wend '// Rest of your code, presumably something like: Set Doc = IE.Document Set results = Doc.getElementsByClassName("a-size-large a-color-price olpOfferPrice a-text-bold") If results.Length > 0 Then '// Rest of code here ..... End Sub