【问题标题】:Get text inside a <p> element inside span tag with VBA使用 VBA 在 span 标签内的 <p> 元素内获取文本
【发布时间】:2018-12-17 09:59:35
【问题描述】:

我有以下 html 部分

<div>
<p class="wholesaletext"> Χονδρική Τιμή:&nbsp;<br/>
<span id="our_price_display" class="price" itemprop="price" content="9.9">
<p class="wholesaletext">9,90 €
</span> &chi;&omega;&rho;ί&sigmaf; &Phi;.&Pi;.&Alpha;
<meta itemprop="priceCurrency" content="EUR" />                             
</p>
</p>
</div>

我正在尝试使用以下内容从上面获取&lt;p class=wholesaletext"&gt; 的文本

Set price = ie.Document.getElementsByTagName("span")
Dim lnk As Variant        

 For Each lnk In price
    If lnk.className = "price" Then
        wks.Cells(i, "E").Value = lnk.innerText
        Exit For
    End If
 Next

我在单元格中什么都没有。

我试过了

Set price = ie.Document.querySelector(".price .wholesaletext")
wks.Cells(i, "E").Value = price.innerText

我什么也得不到。

我试过了

Set price = ie.Document.getElementsByTagName("p")
Dim lnk As Variant        

For Each lnk In price
    If lnk.className = "wholesale" Then
        wks.Cells(i, "E").Value = lnk.innerText
        Exit For
    End If
Next

但它在 html 中得到另一个文本,而不是价格。

【问题讨论】:

  • 试试 .wholesaletext 并等待

标签: excel vba web-scraping


【解决方案1】:

获取实际文本的更好方法是使用 .wholesaletext 的 css 类选择器 所以,

ie.document.querySelectorAll(".wholesaletext")

然后通过索引访问文本和带有价格的文本

ie.document.querySelectorAll(".wholesaletext").item(0).innerText
ie.document.querySelectorAll(".wholesaletext").item(1).innerText

CSS:

【讨论】:

    【解决方案2】:

    为什么不首先使用id 而不是标签名称,然后像这样:price = ie.Document.getElementByid("our_price_display"),然后是您将使用的价格price.getAttribute("content"),这样就可以了:

    Set price = ie.Document.getElementByid("our_price_display")
    
    wks.Cells(i, "E").Value = price.getAttribute("content")
    

    【讨论】:

    • 它正在工作,但是当我尝试将其转换为货币时,我得到 0,00 欧元,为什么?
    • @Nikos 可能是因为内容是字符串数据类型,您需要一个双精度才能将其转换为货币 - 这应该可以解决这个问题:wks.Cells(i, "E").Value = CDbl(price.getAttribute("content"))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多