【问题标题】:VBA to loop through multiple HTML tablesVBA循环遍历多个HTML表格
【发布时间】:2018-01-05 00:05:26
【问题描述】:

这是我试图仅返回价格值的链接:https://www.express-supp...

我有一个 VBA 脚本,它将所有 product-grid-details 表值返回到工作簿中,但有些值进入了错误的列,不允许生成数据透视表。但是,如果我更改此代码以生成名为 price-box 的表,它根本不会返回任何值。

我认为页面上的 HTML 表格是乱序的,并且彼此之间没有排序,这就是它使数据超出列的原因。作为一种解决方案,我希望 VBA 只返回页面的项目名称和价格,而不是全部。我该怎么做?

选择返回 product-grid-details 时如何将表格返回到工作簿的示例:

代码如下:

     With CreateObject("WINHTTP.WinHTTPRequest.5.1")
    .Open "GET", "https://www.express-supplements.co.uk/catalogsearch/result?q=Optimum+Nutrition", False
    .send
    oHtml.body.innerHTML = .responseText
    Debug.Print
 End With

 ReDim a(1 To 100000, 1 To 60)
 For Each oElement In oHtml.getElementsByClassName("product-grid-details")
    i = i + 1
    x = Split(oElement.innerText, vbCr)

    For ii = 1 To UBound(x)
        a(i, 1) = nowDate
        a(i, 2) = nowTime
        a(i, 3) = weblinks(webX, 1)
        a(i, 4) = weblinks(webX, 2)
        a(i, ii + 4) = Trim$(x(ii))
    Next

 Next oElement

    With SHwebdata
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        .Cells(LastRow + 1, 1).Resize(i, UBound(a, 2)) = a
        i = 0
    End With

【问题讨论】:

    标签: vba excel web-scraping html-table


    【解决方案1】:

    给你。只需运行它并获得您要求的结果:

    Sub Web_Data()
        Dim http As New XMLHTTP60, html As New HTMLDocument
        Dim topic As HTMLHtmlElement
    
        With http
            .Open "GET", "https://www.express-supplements.co.uk/catalogsearch/result?q=Optimum%20Nutrition", False
            .send
            html.body.innerHTML = .responseText
        End With
    
        For Each topic In html.getElementsByClassName("product-grid-details")
            With topic.getElementsByClassName("product-name")
                If .Length Then x = x + 1: Cells(x, 1) = .item(0).innerText
            End With
            With topic.getElementsByClassName("price")
                If .Length Then Cells(x, 2) = .item(0).innerText
            End With
        Next topic
    End Sub
    

    【讨论】:

    • 你是个天才!完美运行!
    • 您能否看看这个link,看看是否可以使用与您刚刚发布的相同的方法从多个表中返回项目名称和价格?我认为它应该跟随 getElementsByClassName("category-products") 然后 ("product-name")("price")但由于某种原因它不起作用。难道是 .Item(0) 数字必须更改才能返回值?
    • 没问题。只需打开一个新线程并在此处提供链接。我要调查一下。谢谢。
    猜你喜欢
    • 2017-11-26
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 2017-02-11
    • 1970-01-01
    • 2017-10-19
    • 2021-06-28
    相关资源
    最近更新 更多