【问题标题】:how to get all child elements of a parent in selenium vba?如何在 selenium v​​ba 中获取父级的所有子元素?
【发布时间】:2020-12-15 21:42:33
【问题描述】:
Option Explicit

Sub ex()
Dim htmldoc As MSHTML.HTMLDocument

Dim htmldiv As Selenium.WebElement
Dim htmlul As Selenium.WebElement
Dim htmlAs As Selenium.WebElements
Dim htmlA As Selenium.WebElement
Dim htmlTable As Selenium.WebElement
Dim TableSection As Selenium.WebElement

Dim TableName As String

URL = "https://www.whoscored.com/Statistics"

sel.Start "Chrome"
sel.Get URL
 
Set htmldiv = sel.FindElementById("top-player-stats")
Set htmlul = sel.FindElementById("top-player-stats-options")

Set htmlAs = htmlul.FindElementsByTag("a")

    For Each htmlA In htmlAs
        TableName = Right(htmlA.Attribute("href"), Len(htmlA.Attribute("href")) - InStr(1, htmlA.Attribute("href"), "#"))
        htmlA.Click
        
Set htmlTable = sel.FindElementById(TableName & "-grid")
    
    For Each TableSection In htmlTable.FindElementsByXPath("//*[@id=""top-player-stats-summary-grid""]")
        'Debug.Print htmlTable.FindElementsByXPath("//*[@id=""top-player-stats-summary-grid""]").Count
        debug.print TableSection.tagname

    Next TableSection

    Next htmlA
End Sub

这里 htmltable.findelementsbyxpath... 只给出一个元素,即 table 标记本身,但我想循环遍历 htmltable 的所有子项,那么该怎么做。我的 xpath 方法是否正确?

【问题讨论】:

  • 取决于最终目的。有一种方法可以一次性将表格写入工作表,而无需循环可用的 .AsTable.ToExcel。否则,你想循环 tr 然后 td。
  • 我们不能使用 children 属性或 xpath 之类的东西循环遍历子表吗?
  • 我是说既然可以用webdriver的现有方法一口气写出来,为什么还要循环呢?
  • 如果有现有的方法,那该怎么做呢?

标签: vba selenium xpath


【解决方案1】:

您可以构建一个 udf 并实现 childElementCount 和 childNodes。 在您的代码中,您可以使用以下方法对其进行测试:

Debug.Print sel.WebDriver.ExecuteScript("return arguments[0].childElementCount", TableSection)

Debug.Print sel.WebDriver.ExecuteScript("return arguments[0].childNodes[0].tagName", TableSection)
Debug.Print sel.WebDriver.ExecuteScript("return arguments[0].childNodes[1].tagName", TableSection)

并使用此策略为其子元素更改 TableSelection 元素

【讨论】:

  • 可以去掉()
猜你喜欢
  • 1970-01-01
  • 2021-12-25
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-11
相关资源
最近更新 更多