【问题标题】:How to grab a portion of a website text into an Excel cell如何将网站文本的一部分抓取到 Excel 单元格中
【发布时间】:2016-12-08 08:19:41
【问题描述】:

我正在尝试自动从 GM Parts 网站为一系列零件编号值创建描述列表。

例如,以下是部件号 23498355 的链接 - http://www.gmpartsdirect.com/oe-gm/23498355

我正在尝试获取零件描述文本“此 ABS 传感器是真正的 OEM GM 零件 #23498355 并提供工厂保修。我们提供最优惠的在线价格,并为我们下的任何订单提供快速发货。”可在此网页上导入 Excel。

我编写了以下代码来获取该信息,但无法完成可以获取此特定信息的最后几行。

Option Explicit

Sub myConnection()
    Dim oHtml, myData, Title, cste
    Set oHtml = New HTMLDocument
    With CreateObject("WINHTTP.WinHTTPRequest.5.1")
        .Open "GET", "http://www.gmpartsdirect.com/oe-gm/23498355", False
        .send
        oHtml.body.innerHTML = .responseText
    End With
'Rest of the code to grab the exact part description
End Sub

一旦我完成这项工作,我的想法就是自动化处理零件编号列表。 谁能帮我完成这段代码?

【问题讨论】:

    标签: excel vba webpage html-object


    【解决方案1】:

    使用 MSHTML 解析您的 HTML 有点受限,因为许多“现代”文档方法可能无法实现,但您可以让它在这种情况下工作:

    Sub myConnection()
        Dim oHtml, myData, Title, cste, d
        Set oHtml = New MSHTML.HTMLDocument
    
    
        With CreateObject("WINHTTP.WinHTTPRequest.5.1")
            .Open "GET", "http://www.gmpartsdirect.com/oe-gm/23498355", False
            .send
            oHtml.body.innerHTML = .responseText
    
            Set d = myGetElementsByClassName(oHtml, "div", "description_body")
            If Not d Is Nothing Then
                Debug.Print d.innerText
            End If
    
        End With
    'Rest of the code to grab the exact part description
    End Sub
    
    
    'return an element given its tag name and class name
    Function myGetElementsByClassName(doc, tagName, className) As Object
        Dim el As Object
        For Each el In doc.getElementsByTagName(tagName)
            If el.className = className Then
                Set myGetElementsByClassName = el
                Exit Function
            End If
        Next el
        Set myGetElementsByClassName = Nothing
    End Function
    

    【讨论】:

    • 对于像我这样的菜鸟,请通过单击 VBA 窗口中的 工具 -> 参考.. -> Microsoft HTML 对象库 来激活 Microsoft HTML 对象库
    猜你喜欢
    • 2020-12-23
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    相关资源
    最近更新 更多