如何使用 Selenium 和 Python 提取表格中的列标题?
可以使用 Selenium 提取表格中的列标题。表格的标题由 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()
# identifying the header from row1 having <th> tag
heads = driver.find_elements_by_xpath("//table/tbody/tr[1]/th")
# len method is used to get the size of that list
print(len(heads))
for h in heads:
print(h.text)
#to close the browser
driver.close()
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP