使用 getElementsByClassName 时出错 "Object variable or with block variable not set"

Error "Object variable or with block variable not set" when using getElementsByClassName

我想从亚马逊上回收一些字段。

Atm 我正在使用 link 和我的 vba 脚本 returns 我的名字和价格。

例如:

我将 link 放入 A 列并获取相应列中的其他字段,f.ex。:http://www.amazon.com/GMC-Denali-Black-22-5-Inch-Medium/dp/B00FNVBS5C/ref=sr_1_1?s=outdoor-recreation&ie=UTF8&qid=1436768082&sr=1-1&keywords=bicycle

不过,我也想要product description

这是我当前的代码:

Sub ScrapeAmz()

 Dim Ie As New InternetExplorer
 Dim WebURL
 Dim Docx As HTMLDocument
 Dim productDesc
 Dim productTitle
 Dim price
 Dim RcdNum

Ie.Visible = False

For RcdNum = 2 To ThisWorkbook.Worksheets(1).Range("A65536").End(xlUp).Row

    WebURL = ThisWorkbook.Worksheets(1).Range("A" & RcdNum)
     Ie.Navigate2 WebURL
     Do Until Ie.ReadyState = READYSTATE_COMPLETE
     DoEvents
     Loop
     Set Docx = Ie.Document
     productTitle = Docx.getElementById("productTitle").innerText
     'productDesc = Docx.getElementsByClassName("productDescriptionWrapper")(0).innerText
     price = Docx.getElementById("priceblock_ourprice").innerText
     ThisWorkbook.Worksheets(1).Range("B" & RcdNum) = productTitle
     'ThisWorkbook.Worksheets(1).Range("C" & RcdNum) = productDesc
     ThisWorkbook.Worksheets(1).Range("D" & RcdNum) = price
   Next

End Sub

我正在尝试使用 productDesc = Docx.getElementsByClassName("productDescriptionWrapper")(0).innerText 获取产品描述。

但是,我得到一个错误。

Object variable or with block variable not set.

为什么我的陈述不起作用有什么建议吗?

感谢您的回复!

我很确定您的问题是由于在文档完全加载之前尝试访问它造成的。您只是检查 ie.ReadyState.

这是我对使用IE控件加载页面的时间轴的理解。

  1. 浏览器连接到页面:ie.ReadyState = READYSTATE_COMPLETE。此时,您可以访问 ie.document 而不会导致错误,但文档才刚刚开始加载。
  2. 文档已完全加载:ie.document.readyState = "complete" (请注意,帧可能仍在加载并且 AJAX 处理可能仍在进行。)

所以你真的需要检查两个事件。

Do
    If ie.ReadyState = READYSTATE_COMPLETE Then
        If ie.document.readyState = "complete" Then Exit Do
    End If
    Application.Wait DateAdd("s", 1, Now)
Loop

编辑:在实际查看您尝试抓取的页面后,它失败的原因似乎是因为您尝试获取的内容位于 iframe 中。您需要通过 iframe 才能获取内容。

ie.document.window.frames("product-description-iframe").contentWindow.document.getElementsByClassName("productDescriptionWrapper").innerText