如何在使用Python和Selenium的條件下獲取工作表中特定行的所有值?
我們可以使用Selenium獲取工作表中特定行的所有值,基於一定的條件。Excel是一個以.xlsx副檔名儲存的電子表格。一個Excel工作簿包含多個工作表,每個工作表由行和列組成。
在我們訪問特定工作表時,它被稱為活動工作表。工作表中的每個單元格都有一個唯一的地址,它是行號和列號的組合。
列號從字母A開始,行號從數字1開始。單元格可以包含多種型別的值,它們是工作表的主要組成部分。
要在Python和Selenium中使用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 check the value in column 1 if(sh.cell(row=r, column=1).value == "2": # to traverse through the columns for c in range(2,max_column+1): # to get all the values print(sh.cell(row=r, column=c).value)
我們引用的Excel資料: