无法使用vba获取第n个span元素的文本

时间:2018-12-11 10:46:05

标签: excel vba excel-vba web-scraping

我有以下html部分

<div class="description">
<span>Brand:</span> 
<a href="http://www.bestfamily.gr">Nikon</a><br/>
<span>Product Code:</span> 130342 <br/>
<span>Barcode</span> 18208948581 <br/>
<span>Availability:</span>Available</div>

我正在尝试使用以下命令获取最后一个跨度和可用字样

Set availability = ie.Document.getElementsByClassName(".description").getElementsByTagName("span")(2)
wks.Cells(i, "D").Value = availability.innerText

但是它显示所有跨度文本 我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

last-child中将descendant combination css伪类与父元素class selector一起使用。

.description span:last-child
  

:last-child CSS伪类表示一个元素中的最后一个元素   一组同级元素。

正在应用:

单场比赛

Set availability = ie.document.querySelector(".description span:last-child")
Cells(1,1) = availability.innerText

所有比赛

Set availability = ie.document.querySelectorAll(".description span:last-child")
Cells(1,1) = availability.item(0).innerText

否则,您可以从该父类返回span集合并对其进行索引

Set availability = ie.document.querySelectorAll(".description span")
Cells(1,1) = availability.item(2).innerText '<==choose your index here

甚至连锁:

Set availability = ie.document.querySelector(".description span + span + span")  '<==expand as required. This uses [adjacent sibling combinator][4].

遗憾的是,VBA实现不支持伪类nth-of-type / nth-child,尽管您可以使用许多其他语言,例如python。

-

如果仅在可用之后,您应该可以使用.description作为选择器来返回div中的所有文本。然后使用Chr $(32)在.innerText上使用Split进行拆分并提取UBound(即生成的数组的最后一个元素)

Set availability = ie.document.querySelector(".description")
Dim arr() As String
arr = split( availability.innerText, ":")
Cells(1,1) = arr(UBound(arr))

答案 1 :(得分:0)

正如Zac在评论中指出的那样,您不应该在.方法中使用句点getElementsByClassName

ie.Document.getElementsByClassName返回元素的DispHTMLElementCollection。您需要指定要引用的元素

  

设置可用性= ie.Document.getElementsByClassName(“。description”)(0).getElementsByTagName(“ span”)(2)

编写代码的更好方法是引用Microsoft HTML对象库并创建一个变量来测试返回的每个元素。不幸的是,DispHTMLElementCollection实现中存在错误,因此您将需要使用Object而不是DispHTMLElementCollection

Dim doc As HTMLDocument
Dim availability As Object
Set doc = ie.Document
Set availability = doc.getElementsByClassName("description")

Dim div As HTMLDivElement
Dim span As HTMLSpanElement
Dim spans As Object

For Each div In availability
    Set spans = div.getElementsByTagName("span")
    For Each span In spans
        Debug.Print span.innerText
    Next
Next    

输出

enter image description here

相关问题