使用 Selenium VBA 从 Web 表中的最后过滤行获取数据

Get a data from the last filtered row in a webtable with Selenium VBA

我不是 VBA 方面的专家,而且我对 VBA 的 Selenium 完全陌生。我正在尝试访问这个网站 https://www.tablefilter.com/0-configuration.html ,它有一个带过滤器的 table ,然后根据国家/地区特定标准进行过滤。在那之后,我应该能够转到为这个国家过滤的最后一行,在本例中是“俄罗斯”,将年份复制到 Excel 单元格 B1 中。考虑到这种情况 returns 1998 年、1999 年和 2000 年的三行,我不知道最后该怎么做,但在“斯洛伐克共和国”的情况下,结果只有一行并且例如“津巴布韦”有七行。无论如何,我需要能够为任何国家/地区获取此 table 或唯一记录的最后一行的年份,并了解它们是动态记录。 预先非常感谢。

到目前为止,这是我的代码

Sub Filtros()

Dim bot As New WebDriver
''Dim Sbutton As Selenium.WebElement
''Dim lista As Selenium.SelectElement
Dim Keys As New Selenium.Keys
        
bot.Start "chrome"
bot.Get "https://www.tablefilter.com/0-configuration.html"

''Application.Wait (Now + TimeValue("00:00:02"))
bot.FindElementById("flt0_demo").SendKeys "Russia"
bot.FindElementById("flt0_demo").SendKeys Keys.Enter

Stop

End Sub

您可以在 table 过滤后使用 css selector list 过滤可见行。然后,您需要使用 .Count.

将匹配的 webElements 集合中的最后一个 webElement 设置在变量中
Dim elems As WebElements, last As WebElement

Set elems = bot.FindElementsByCss("#demo tbody > tr:not([style]) > td:nth-child(3)")

Set last = elems.item(elems.Count)

Debug.Print last.Text

table 过滤将值为 display: none;style 属性添加到不在 table 中显示的行。排除 table 正文中具有 style 属性 tbody > tr:not([style]) 的行,允许只匹配可见行。然后,select 代表第 3 列(年份), > td:nth-child(3),取最后一个。


根据您的初始文本输入,您可能需要等待某种形式的过滤才能应用。这可以通过使用定时循环(以避免无限循环)来实现,其中一个退出条件是超过循环的最大时间,另一个是:

bot.findElementsByCss("#demo tbody > tr[style]").count > 0

以先到者为准退出。

或者,使用内置超时机制并尝试匹配隐藏行(这意味着至少对一行进行了过滤):

Dim hiddenRow As WebElement

Set hiddenRow = bot.FindElementByCss("#demo tbody > tr[style]", timeout:=<enter timeout>, Raise:=False)

If hiddenRow Is Nothing Then Exit Sub