如何在 Selenium 和 Python 中根據工作表中的條件獲取特定列的所有值?


我們可以在 Selenium 中根據工作表中的條件獲取特定列的所有值。Excel 是一種電子表格,以 .xlsx 副檔名儲存。一個 Excel 工作簿包含多個工作表,每個工作表由行和列組成。

在所有工作表中,當我們訪問一個特定工作表時,它被稱為活動工作表。工作表中的每個單元格都有一個唯一的地址,它是行號和列號的組合。

列號從字母字元 A 開始,行號從數字 1 開始。單元格可以包含多種型別的值,它們是工作表的主要組成部分。

要在 Selenium 和 Python 中使用 Excel,我們需要藉助 OpenPyXL 庫。此庫負責 Excel 的讀寫操作,其副檔名包括 xlsx、xlsm、xltm、xltx。

要安裝 OpenPyXL 庫,我們必須執行命令 **pip install openpyxl**。這是因為 OpenPyXL 不是 Python 的預設庫。之後,我們應該在程式碼中 **import openpyxl**,然後我們就可以與 Excel 互動了。

要獲取特定列的值,首先我們需要透過指定其所在路徑載入整個工作簿。這是透過 load_workbook() 方法實現的。接下來,我們需要藉助 active 方法識別所有工作表中的活動工作表。

接下來,我們需要使用 max_row 方法,該方法提供已佔用行的數量。請注意,此方法應與工作表級物件一起使用。

並且我們需要使用 max_column 方法,該方法提供已佔用列的數量。請注意,此方法應與工作表級物件一起使用。

我們需要從 1 迭代到已佔用最大行數,以遍歷所有行。假設我們的期望值位於第 1 列。因此,我們需要檢查該值是否存在。

如果該值存在,我們需要從 1 迭代到已佔用最大列數,以遍歷所有列。

最後,要檢索該特定列中的所有值,我們需要藉助行號、列號和 cell 方法[它接受行號和列號作為引數]。例如,要指向對應於第 2 行和第 3 列的單元格,我們需要指定 sheet.cell(row=2,column=3)。

語法

wrkbk = load_workbook("C:\work\SeleniumPython.xlsx")
# to identify the active sheet
sh = wrkbk.active
# identify the number of occupied rows
sh.max_row
# identify the number of occupied rows
sh.max_column

示例

獲取特定列所有值的程式碼實現。

import openpyxl
# load excel with its path
wrkbk = load_workbook("C:\work\SeleniumPython.xlsx")
# to get the active work sheet
sh = wrkbk.active
# to print the maximum number of occupied rows in console
print(sh.max_row)
# to print the maximum number of occupied columns in console
print(sh.max_column)
# to get all the values from the excel and traverse through the rows
for r in range(1,max_row+1):
# to traverse through the columns
for c in range(i,max_column+1):
# to check the value in row 1
if(sh.cell(row=1, column=c).value == "Tutorial":
# to get all the values
print(sh.cell(row=r, column=c).value)

我們引用的 Excel 資料 -

更新於: 2020-07-29

724 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告