如何使用 Python 中的 Selenium 统计表格中的行数?


我们可以在 Selenium 中统计表格中的总行数。表格中的行由 html 代码中的 <tr> 标记表示。要获取所有行,我们将使用定位器 xpath,然后使用 find_elements_by_xpath 方法。系统会返回行列表。接下来,我们需要借助 len 方法计算该列表的大小。

以下是表格行计数的 html 代码段描述−

语法

driver.find_elements_by_xpath("//table/tbody/tr")

示例

获取行计数的代码实现。

from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://tutorialspoint.com/plsql/plsql_basic_syntax.htm")
#to refresh the browser
driver.refresh()
# identifying the number of rows having <tr> tag
rows = driver.find_elements_by_xpath("//table/tbody/tr")
# len method is used to get the size of that list
print(len(rows))
#to close the browser
driver.close()

更新于: 2020 年 7 月 29 日

11K+ 次浏览

开启你的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.