如何使用 Python 和 Selenium 從表格中獲取特定單元格的值(例如第二行第二列)?
我們可以從 Selenium 中表格的特定單元格(例如第二行第三列)中提取值。首先,我們需要使用 xpath 定位器找到該單元格。
由於給定了行號和列號,我們可以使用 <tr> 和 <td> 標記指定的索引建立一個自定義 xpath。表格的行在 html 程式碼中由 <tr> 標記表示。每行中的資料在 html 中用 <td> 標記括起來。因此,<td> 標記的父級始終是 <tr> 標記。
因此,要獲取第二行第二列的值,我們必須將行指定為 tr[2],第三列將被識別為 td[2]。
語法
driver.find_element_by_xpath("//table/tbody/tr[2]/td[2]")表格標題的 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 data from 2nd row and 2nd column directly
val = driver.find_elements_by_xpath("//table/tbody/tr[2]/td[2]").text
# print the value in console
print(val)
#to close the browser
driver.close()
廣告
資料結構
網路
關係型資料庫
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP