处理下拉列表需要用到 Selenium 里的 Select 工具类,Select 的方法和属性如下表所示:
| 属性/方法 | 属性/方法描述 |
|---|---|
| options | 所有选项 |
| all_selected_options | 所有选中的选项 |
| first_selected_option | 首个选中的选项 |
| select_by_value() | 根据value值选择 |
| select_by_index() | 根据索引选择 |
| select_by_visible_text | 根据文本选择 |
| deselect_all() | 反选所有选项 |
| deselect_by_value() | 根据value值反选 |
| deselect_by_index | 根据索引反选 |
| deselect_by_visible_text | 根据文本反选 |
使用方法:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>测试下拉表单</title></head><body><!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>测试 checkbox 和 radio button</title></head><body><form action="javascript:alert('test')"><select name="fruit" id="fruit" multiple style="height:100px"><option value="apple" selected>apple</option><option value="banana" selected>banana</option><option value="peach">peach</option><option value="mango">mango</option><option value="pear">pear</option></select><input type="submit" value="submit"></form></body></html></body></html>
from selenium import webdriverfrom time import sleepfrom os import pathfrom os.path import joinfrom selenium.webdriver.support.select import Selectclass TestCase(object):def __init__(self):demo03_path = path.dirname(path.abspath(__file__))form_path = join(demo03_path, 'form2.html')self.driver = webdriver.Chrome()self.driver.maximize_window()self.driver.get(form_path)def test_select(self):"""测试 下拉列表 的方法:return:"""sleep(1)fruit = self.driver.find_element_by_id('fruit')fruits = Select(fruit)# 1、获取所有选项,打印选项数量option = fruits.optionsprint(len(option))# 2、获取所有被选中的选项,打印被选中选项的文本内容selected = fruits.all_selected_optionsfor f in selected:print(f.text)# 3、打印第一个选中的选项的文本内容first_select = fruits.first_selected_optionprint(first_select.text)# 4、选中value值为 peach 的选项fruits.select_by_value('peach')sleep(1)# 5、选中第4个选项,即选中 mangofruits.select_by_index(3)sleep(1)# 6、选中文本内容为 pear 的选项fruits.select_by_visible_text('pear')sleep(1)# 7、反选所有选项fruits.deselect_all()sleep(1)# 选中所有选项for f in option:fruits.select_by_visible_text(f.text)sleep(1)# 8、反选value值为 apple 的选项fruits.deselect_by_value('apple')sleep(1)# 9、反选第2个选项fruits.deselect_by_index(1)sleep(1)# 10、反选文本内容为 peach 的选项fruits.deselect_by_visible_text('peach')if __name__ == '__main__':case = TestCase()case.test_select()
运行过程:
打印结果:
