如何使用 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.tw/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+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告