如何使用 Python 和 Selenium 統計頁面中表格的總數?
我們可以藉助 find_elements 方法來統計 Selenium 頁面中表格的總數。在處理任何表格時,我們總是會在 HTML 程式碼中找到標籤名,其值應為 table (<table>)。
此特性僅適用於該頁面上的表格,而不適用於其他型別的 UI 元素,如編輯框、單選按鈕等。
要檢索所有標籤名為 table 的元素,我們將使用 find_elements_by_tag_name() 方法。此方法返回一個 Web 元素列表,其型別是在方法引數中指定的標籤名。如果沒有匹配的元素,則返回一個空列表。
獲取表格列表後,為了計算其總數,我們需要獲取該列表的大小。列表的大小可以透過列表資料結構的 len() 方法獲得。
最後,此長度將列印到控制檯。
語法
driver.find_elements_by_tag_name("table")
示例
統計表格數量的程式碼實現。
from selenium import webdriver 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/index.htm") #to refresh the browser driver.refresh() #to get the list of tables present on the web page t = driver.find_elements_by_tag_name('table') #print the count with the len method on console print(len(t)) #to close the browser driver.quit()
廣告