【问题标题】:VBA scrape src instead of hrefVBA 抓取 src 而不是 href
【发布时间】:2018-02-08 17:25:14
【问题描述】:

我正在使用代码下面的代码,但由于某种原因它带来了“src”而不是“href”的值。有人可以帮忙吗?

Sub bringfox(txt As String)

Dim oHtml       As HTMLDocument
Dim oElement    As Object
Set oHtml = New HTMLDocument

maintext2 = "https://www.jjfox.co.uk/cigars/show/all.html"

With CreateObject("WINHTTP.WinHTTPRequest.5.1")
    .Open "GET", maintext2 & gr, False
    .send
    oHtml.body.innerHTML = .responseText
End With



counter = cnt
'oElement(i).Children(0).getAttribute ("href")
Set oElement = oHtml.getElementsByClassName("products-grid products-grid--max-3-col")(0).getElementsByTagName("a")
i = 0
While i < oElement.Length
    Debug.Print oElement(i).Children(0).getAttribute("href")

    i = i + 1

Wend


End Sub

【问题讨论】:

  • 这里的 txt 和 gr 是什么?

标签: vba excel href scrape


【解决方案1】:

您可以尝试使用CSS selector

#wrapper div.category-products > ul a

这是完整选择器的简化版本,针对产品类别中的 a 标记。然后解析 outerHTML 的 href,因为这是信息所在的位置。


网站图片(示例视图)


代码输出(示例视图)


代码

Option Explicit
Public Sub GetInfo()
    Dim oHtml As HTMLDocument, nodeList As Object, currentItem As Long
    Const URL As String = "https://www.jjfox.co.uk/cigars/show/all.html"
    Set oHtml = New HTMLDocument
    With CreateObject("WINHTTP.WinHTTPRequest.5.1")
        .Open "GET", URL, False
        .send
        oHtml.body.innerHTML = .responseText
    End With

    Set nodeList = oHtml.querySelectorAll("#wrapper div.category-products > ul a")
    For currentItem = 0 To nodeList.Length - 1
        On Error Resume Next
        Debug.Print Split(Split(nodeList.item(currentItem).outerHTML, "<A href=")(1), ">")(0)
        On Error GoTo 0
    Next currentItem
End Sub

或者更简单地说,使用下面的

For currentItem = 0 To nodeList.Length - 1
    On Error Resume Next
    Debug.Print nodeList.item(currentItem).href
    On Error GoTo 0
Next currentItem

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多