如何使用 Python 和 Selenium 獲取工作表中的所有值?


我們可以使用 Selenium 獲取工作表中的所有值。Excel 是一種電子表格,以 .xlsx 副檔名儲存。一個 Excel 工作簿包含多個工作表,每個工作表都包含行和列。

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

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

要在 Python 中使用 Selenium 處理 Excel,我們需要藉助 OpenPyXL 庫。此庫負責對 Excel 進行讀寫操作,處理 xlsx、xlsm、xltm、xltx 等副檔名。

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

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

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

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

我們需要從 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

示例

獲取 Excel 中所有值的程式碼實現。

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(1,max_column+1):
# to get all the values
      print(sh.cell(row=r, column=c).value)

更新於: 2020-07-29

341 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.