从'嵌套'中删除数据iframe与vba

时间:2017-11-01 19:15:54

标签: vba excel-vba iframe excel

我试图从mcmaster.com中删除标题和价格,以自动填充内部购买结算表单。 (带有项目部件号的URL在下面用硬编码进行测试。)标题很好,但无法获得价格。我不认为我的代码正在查找正确的位置,因为找不到该元素。我从here.

建模了我的代码
Sub get_title_header()
Dim wb As Object
Dim doc As Object
Dim sURL As String

Set wb = CreateObject("internetExplorer.Application")
sURL = "https://www.mcmaster.com/#95907A480"

wb.navigate sURL
wb.Visible = True

While wb.Busy Or wb.readyState <> READYSTATE_COMPLETE
    DoEvents
Wend

'Wait a bit for everything to catchup...(network?)
Application.Wait (Now + TimeValue("0:00:02"))

'HTML document
Set doc = wb.document

Dim MyString As String
MyString = doc.Title

Sheet2.Cells(1, 2) = Trim(Replace(MyString, "McMaster-Carr -", "", , , vbTextCompare))

Dim el As Object
For Each el In doc.getElementsByName("Prce")
    Sheet2.Cells(2, 2).Value = el.innerText
Next el

wb.Quit

End Sub

这个iframe是否嵌套?任何人都可以解释为什么我的代码无法看到iframe数据并帮助我获得商品价格?提前谢谢!

1 个答案:

答案 0 :(得分:1)

您尝试在链接中抓取的元素嵌套如下:

enter image description here

你犯的第一个错误就是你试图通过System.out.println(new File("").getAbsolutePath()); 获取此对象,而不是name

id

HTML文档中没有名称=“Prce”的对象,所以我希望doc.getElementsByName("Prce") 周期甚至不开始。

您可能想要获得的价格是:

For

其中:

  • Sheet2.Cells(2, 2).Value = doc.getElementById("Prce").getElementsByClassName("PrceTxt")(0).innerText 为您提供元素doc.getElementById("Prce")
  • <div id="Prce">...</div>为您提供上述div中的第一个(也是唯一的)元素,即.getElementsByClassName("PrceTxt")(0)
  • <div class="PrceTxt">...</div>为您提供此元素的文字