VBA从HTML中获取属性值

时间:2014-09-18 08:04:23

标签: excel vba excel-vba

我正在尝试创建宏,它将从特定属性中获取数据,只需粘贴在excel上,我使用getElementsById尝试了它,但它对我不起作用。

我有链接:
https://secure.bmw.com/_common/silo/pages/form-tabs/controller_opt.jsp?locale=XQ_en&usercountry=IN&tracking_usercountry=IN&tracking_locale=XQ_en&transfer=f23_info_req_lp

只需查看来源,您就会找到属性名称“引导上下文”

<input type="hidden" name="reg_source" value="OPK">
<input type="hidden" name="lead_context" value="F45CV ROI OPK">
<input type="hidden" name="subscription_lead_context" value="F45CV ROI OPK">
<input type="hidden" name="cam_source_code" value="1-1521452141">
<input type="hidden" name="offer_code" value="1524521452">

所以基本上我想要excel表上的值“OPK”,“F45CV ROI OPK”,“1-1521452141”和“1524521452”。

任何人都可以用简单的代码帮助我,很抱歉因为我是VBA的新手。

感谢您的时间:)

此致 MAYUR

1 个答案:

答案 0 :(得分:1)

一种方法是获取所有<input>元素并循环遍历它们以收集您需要的内容。我使用的变量赋值需要工具,引用,Microsoft HTML对象库,但如果您愿意,可以将它们称为对象。

Dim eNPT As MSHTML.IHTMLElement, ecNPTs As MSHTML.IHTMLElementCollection
Set ecNPTs = ie.document.getElementsByTagName("input")
Range("A1:A5").ClearContents
For Each eNPT In ecNPTs
    Select Case LCase(eNPT.getAttribute("name"))
        Case "reg_source"
            Range("A1") = eNPT.Value
        Case "lead_context"
            Range("A2") = eNPT.Value
        Case "subscription_lead_context"
            Range("A3") = eNPT.Value
        Case "cam_source_code"
            Range("A4") = eNPT.Value
        Case "offer_code"
            Range("A5") = eNPT.Value
        End Select
        If Application.CountA(Range("A1:A5")) = 5 Then Exit For
Next eNPT
Set ecNPTs = Nothing: Set eNPT = Nothing