如何取消静态下拉菜单中的选项选择?
我们可以使用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.com/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()
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP