这篇教程Python写得很实用,希望能帮到您。
一、前言selenium的下拉选择框。我们通常会遇到两种下拉框,一种使用的是html的标签select,另一种是使用input标签做的假下拉框。 后者我们通常的处理方式与其他的元素类似,点击或使用JS等。而对于前者,selenium给了有力的支持,就是Select类。 进行测试的网站:http://sahitest.com/demo/selectTest.htm 网页及对应源码: 
二、关于导入方式两种导入方式: from selenium.webdriver.support.ui import Select# 或者直接从select导入from selenium.webdriver.support.select import Select
三、选择、反选、选项的实战应用例子话不多说,直接上代码: # -*- coding: utf-8 -*- """@author: lucas@Function:@file: selectStudy.py@time: 2021/8/20 1:27 下午"""import unittestimport time from selenium import webdriverfrom selenium.webdriver.support.ui import Select class SelectStudy(unittest.TestCase): def setUp(self): # 创建一个Chrome WebDriver的实例 self.driver = webdriver.Chrome() # 选择页面第一个下拉框,依次选择值O1-O3 def test_selectO1ToO3(self): driver = self.driver driver.get('http://sahitest.com/demo/selectTest.htm') # 实例化Select s1 = Select(driver.find_element_by_id('s1Id')) # 查看选择框的默认值 print s1.first_selected_option.text # 选择第二个选项o1 s1.select_by_index(1) time.sleep(3) # 为了方便查看效果,可以加上等待时间 time.sleep(3) # 选择value="o2"的项,value是option标签的一个属性值,并不是显示在下拉框中的值 s1.select_by_value("o2") # 查看选中选择框的默认值 print s1.first_selected_option.text time.sleep(3) # 选择text="o3"的值,即在下拉时我们可以看到的文本,visible_text是在option标签中间的值,是显示在下拉框的值 s1.select_by_visible_text("o3") time.sleep(3) # 反选操作,包括取消某个值和全部取消 def test_cancel_select(self): driver = self.driver driver.get('http://sahitest.com/demo/selectTest.htm') s4 = Select(driver.find_element_by_id('s4Id')) # 全选 for option in s4.options: if not option.is_selected(): print option.text s4.select_by_visible_text(option.text) time.sleep(3) # 根据index取消选中 s4.deselect_by_index(0) time.sleep(3) # 根据value取消选中 s4.deselect_by_value("o1val") time.sleep(5) # 根据标签文本选中 s4.deselect_by_visible_text("o2") time.sleep(5) # 全选 for option in s4.options: if not option.is_selected(): s4.select_by_visible_text(option.text) time.sleep(3) # 取消选中所有选项 s4.deselect_all() # 查看选中项目 """ 输出结果为: o1 o2 With spaces With nbsp """ def test_view_selection(self): driver = self.driver driver.get('http://sahitest.com/demo/selectTest.htm') s4 = Select(driver.find_element_by_id('s4Id')) # 查看选择框的默认值 s4.select_by_index(1) s4.select_by_value("o2val") s4.select_by_visible_text("With spaces") s4.select_by_value("o4val") for select in s4.all_selected_options: print select.text def tearDown(self): self.driver.close() if __name__ == "__main__": unittest.main() 注意: 反选(deselect)取消操作只适用于添加了multiple的下拉框,否则会报错 raise NotImplementedError("You may only deselect options of a multi-select") NotImplementedError: You may only deselect options of a multi-select
四、总结1、Select提供了三种选择方法: |