如何使用 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.tw/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()
廣告