如何使用 Python 和 Selenium 获取页面中表格内所有值(包括表头)?


我们可以使用 find_elements 方法获取 Selenium 中表格内的所有值。表格的行在 html 代码中由 <tr> 标签表示。要获取所有行,我们将使用定位符 xpath,然后使用 find_elements_by_xpath 方法。将返回行列表。接下来,我们需要使用 len 方法计算列表的大小。

语法

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

获取所有行后,我们现在需要计算列数。

表格的表头在 html 中由 <th> 标签表示,并且始终位于表格的第一行。行在 html 中由 <tr> 标签标识。列标题的数量通常等于列的总数。<th> 标签的父元素始终是 <tr> 标签。

逻辑是获取所有表头。我们将使用定位符 xpath,然后使用 find_elements_by_xpath 方法。将返回表头列表。接下来,我们需要使用 len 方法计算列表的大小。

语法

driver.find_elements_by_xpath("//table/tbody/tr[1]/th")

表格列计数的 html 代码片段如下所示:

示例

获取表格中所有值的编码实现。

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()
# to get the row count of table
rws = driver.find_elements_by_xpath("//table/tbody/tr")
# len method is used to get the size of that list
r = len(rws)
# to get column count of table
cols = driver.find_elements_by_xpath("//table/tbody/tr[1]/th")
# len method is used to get the size of that list
c = len(cols)
el m,nemt = []
#iterate over the rows
for i in range(1,r):
# row data set to 0 each time in list
row = []
#iterate over the columns
   for j in range(1,c):
      # getting text from the ith row and jth column
      d=driver.find_element_by_xpath("//tr["+str(i)+"]/td["+str(j)+"]").text
      row.append(d)
#finally store and print the list in console
elemt.append(row)
print(elemt)
#to close the browser
driver.close()

更新于: 2020-07-29

10K+ 浏览量

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.