html - 如何使用 VBA 从网页中获取产品标题?

标签 html excel vba web-scraping

我现在已经能够搜索谷歌并获得不同 PDP(产品详细信息页面)的不同链接,我想抓取这些页面的产品标题。但是,我无法准确理解如何理解产品标题 html 代码。

下面是我的代码:

Sub testing()


Dim ie As New SHDocVw.InternetExplorer
Dim x As Integer
Dim x1 As Integer
Dim i As Integer
Dim i1 As Integer
Dim Product_Title As String
Dim HTMLDoc As MSHTML.HTMLDocument
Dim htmlinput As MSHTML.IHTMLElement



ie.Navigate "https://www.johnlewis.com/asus-zenbook-ux331un-eg009t-laptop-intel- core-i5-8gb-256gb-ssd-geforce-mx150-13-3-royal-blue/p3405316"

ie.Visible = True

While ie.Busy Or ie.ReadyState < 4: DoEvents: Wend


  Product_Title = ie.document.getElementsByClassName("product-header__title")


   Debug.Print (Product_Title)

但我得到 [object HTMLHeadingElement] 作为输出而不是产品标题

这是html代码:
<h1 class="product-header__title" itemprop="name">ASUS ZenBook S UX391UA-ET087T Laptop, Intel Core i7, 8GB RAM, 256GB SSD, 13.3”, Full HD, Burgundy</h1>

最佳答案

你想要.innerText属性并索引到匹配类名时返回的集合。

ie.document.getElementsByClassName("product-header__title")(0).innerText

与该类名的第一个一样,您也可以使用:
ie.document.querySelector(".product-header__title").innerText
.是一个 CSS class selector querySelector 方法将此应用于 DOM 文档并返回第一个匹配项。

请注意,当您使用您的语法返回集合时,您需要:
Dim Product_Title As Object
Set Product_Title = ie.document.getElementsByClassName("product-header__title")

然后用 Product_Title(0).innerText 索引.我不喜欢在局部变量名中使用下划线,所以我只会使用 productTitle ;另外,请注意外壳的变化。

如果您只是在标题之后,发布 XMLHTTP request 会更快。 ,而不是打开 IE 浏览器实例:
Option Explicit
Public Sub GetTitle()
    Dim sResponse As String, html As HTMLDocument
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.johnlewis.com/asus-zenbook-ux331un-eg009t-laptop-intel-%20core-i5-8gb-256gb-ssd-geforce-mx150-13-3-royal-blue/p3405316", False
        .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
        .send
        sResponse = StrConv(.responseBody, vbUnicode)
    End With

    Set html = New HTMLDocument
    With html
        .body.innerHTML = sResponse
        Debug.Print .querySelector(".product-header__title").innerText
    End With
End Sub

引用资料(VBE > 工具 > 引用资料):
  • Microsoft HTML 对象库
  • 关于html - 如何使用 VBA 从网页中获取产品标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53159463/

    相关文章:

    html - ionic 旋转器未显示在 ionic 化身的中心

    javascript - HTML 或 Javascript 中的随机数生成器

    excel - 免费的 VB6/VBA 分析器和 Excel 最佳实践

    excel - 更改列宽和行高

    excel - 如何 "update"工作簿而不是重新打开它(使用 VBA 宏)?

    javascript - .show 方法在 jQuery 条件中不起作用,而 console.log 显示对象存在

    javascript - 使 href( anchor 标记)请求 POST 而不是 GET 作为传递参数

    vba - 使用单行代码格式化 VBA Excel 中的多个范围

    vba - 使用 VBA 更改 Excel 表单标签长度以匹配其文本的长度

    c# - 读取excel空/空白值