【问题标题】:Get data from the last filtered row in a webtable with Selenium VBA使用 Selenium VBA 从 webtable 中最后过滤的行中获取数据
【发布时间】:2022-07-17 17:02:01
【问题描述】:

我正在尝试访问https://www.tablefilter.com/0-configuration.html,它有一个带有过滤器的表格,然后根据国家/地区特定标准进行过滤。

我想要为该国家/地区过滤的最后一行,在本例中为“俄罗斯”,以便将年份复制到 Excel 单元格 B1 中。此案例返回 1998、1999 和 2000 年的三行。
在“斯洛伐克共和国”的情况下,只有一行。
在“津巴布韦”的情况下,有七行。

对于任何国家,我都需要获取此表最后一行或唯一记录的年份,了解它们是动态记录。

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

【问题讨论】:

    标签: vba selenium web-scraping tablefilter


    【解决方案1】:

    您可以使用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
    

    表格过滤将style 属性值display: none; 添加到表格中不显示的行。排除表体中具有style 属性tbody > tr:not([style]) 的行允许仅匹配可见行。然后,选择第三列(年份) > 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
    

    【讨论】:

    • 谢谢@QHarr。成功了!!!
    猜你喜欢
    • 1970-01-01
    • 2021-07-20
    • 2018-01-16
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 2014-06-01
    相关资源
    最近更新 更多