如何在 Selenium 和 Python 中統計頁面表格內特定文字出現的次數?


我們可以使用 Selenium 統計表格內特定文字出現的次數。首先,我們需要使用 xpath 定位元素。在 xpath 中,我們有一個特定的 text() 函式,它可以根據螢幕上可見的文字識別元素。

然後,我們需要使用 find_elements 方法獲取頁面上包含我們查詢文字的所有匹配元素的列表。最後,我們需要使用列表的 len 函式獲取該列表的大小。

這將給出表格內特定文字出現的次數。

語法

driver.find_elements_by_xpath("//td[text()='Tutorialspoint']")

示例

獲取表格內文字出現次數的程式碼實現。

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 text keyword inside the table
dta = driver.find_elements_by_xpath("//td[text()='keyword']")
# len method is used to get the count of occurrences
print(len(dta))
#to close the browser
driver.close()

更新於: 2020年7月29日

2K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告