如何取消靜態下拉選單中的選項選擇?
我們可以使用Select類中的方法取消靜態下拉選單中的選項選擇。
取消選擇的方法如下:
deselect_by_value(args) − 透過選項的值取消選擇。
此方法根據特定選項的值取消選擇。如果找不到與引數中給定值匹配的值,則會丟擲NoSuchElementException異常。
語法 −
d = Select(driver.find_element_by_id("selection")) d.deselect_by_value('Selenium')
deselect_by_index(args) − 透過選項的索引取消選擇。
此方法根據特定選項的索引取消選擇。元素的索引通常從0開始。如果找不到與引數中給定索引匹配的索引,則會丟擲NoSuchElementException異常。
語法 −
d = Select(driver.find_element_by_id("selection")) d.deselect_by_index(1)
deselect_by_visible_text(args) − 透過選項顯示的文字取消選擇。
此方法是最簡單的方法,它根據可見文字取消選擇選項。如果找不到與引數中給定文字匹配的選項,則會丟擲NoSuchElementException異常。
語法 −
d = Select(driver.find_element_by_id("selection")) d.deselect_by_visible_text('Tutorialspoint')
deselect_all() − 取消所有已選選項的選擇。
此方法適用於可以選擇多個選項的情況。它會刪除下拉選單中所有選定的選項。如果無法從下拉選單中選擇多個選項,則會丟擲NotImplementedError異常。
語法 −
d = Select(driver.find_element_by_id("selection")) d.deselect_all()
示例
下拉選單中選項取消選擇的程式碼實現。
from selenium import webdriver from selenium.webdriver.support.select import Select #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/tutor_connect/index.php") #to refresh the browser driver.refresh() #select class provide the methods to handle the options in dropdown d = Select(driver.find_element_by_xpath("//select[@name='seltype']")) #select an option with visible text method d.select_by_visible_text("By Name") #deselect the option with visible text method d.deselect_by_visible_text("By Name") #select an option with index method d.select_by_index(0) #deselect an option with index method d.deselect_by_index(0) #select an option with value method d.select_by_value("name") #deselect an option with value method d.deselect_by_value("name") #to close the browser driver.close()
廣告