取消所有已选项的方法:
select_element.deselect_all()
取消已选项的三种方法
select_element.deselect_by_visible_text(text)
select_element.deselect_by_index(index)
select_element.deselect_by_value(value)
HTML代码:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>下拉列表</title>
</head>
<body>
<select name = 'fruit' size = 6 multiple=true>
<option id = 'peach' value = 'taozi'>桃子</option>
<option id = 'watermelon' value = 'xigua'>西瓜</option>
<option id = 'orange' value = 'juzi'>橘子</option>
<option id = 'kiwifruit' value = 'mihoutao'>猕猴桃</option>
<option id = 'maybush' value = 'shanzha'>山楂</option>
<option id = 'litchi' value = 'lizhi'>荔枝</option>
</select>
</body>
</html>
多选项测试代码:
from selenium import webdriver
# 导入Sele包
from selenium.webdriver.support.ui import Select
from time import sleep
import unittest
class dropList(unittest.TestCase):
def setUp(self):
self.driver=webdriver.Firefox()
def test_multiple_select(self):
url="file:///F:/workspace/try.html"
self.driver.get(url)
select_element=Select(self.driver.find_element_by_tag_name("select"))
select_element.select_by_value("xigua")
select_element.select_by_index(0)
# select_element.first_selected_option
select_element.select_by_visible_text("荔枝")
for option in select_element.all_selected_options:
print('first-selected-->',option.text)
# 取消所有的已选中项
select_element.deselect_all()
# 重新选择选项
select_element.select_by_value("xigua")
select_element.select_by_index(2)
select_element.select_by_visible_text("山楂")
for option in select_element.all_selected_options:
print('second-selected-->',option.text)
select_element.deselect_by_visible_text('山楂')
for option in select_element.all_selected_options:
print('third-selected-->',option.text)
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()