当前位置: 首页 > 后端技术 > Python

Seleniumselect-下拉列表处理

时间:2023-03-26 15:40:53 Python

对于select标签的下拉列表,Selenium提供了Select类来操作:fromselenium.webdriver.support.uiimportSelectSelect类常用方法:序号方法/属性说明1select_by_value()根据值选择2select_by_index()根据索引选择(从1开始)3select_by_visible_text()根据文本选择4deselect_by_value()根据值取消选择5deselect_by_index()根据索引取消选择6deselect_by_visible_text()根据文本取消选择7deselect_all()deselectall8options获取所有选项9all_selected_options获取所有选中的选项10first_selected_option获取第一个选中的选项selectradiobox对于selectradiobox,操作比较简单。创建Select对象后,可以直接使用Select类中的方法进行选择。示例应用程序fromseleniumimportwebdriverfromtimeimportsleepfromselenium.webdriver.support.uiimportSelectdriver=webdriver.Chrome()#打开浏览器driver.get("http://sahitest.com/demo/selectTest.htm")#跳转到测试页面sleep(1)select_element=Select(driver.find_element_by_id("s1"))#创建Select对象select_element.select_by_value("46")#按值选择sleep(1)select_element.select_by_index(4)#ByindexSelect(startingfrom1)sleep(1)select_element.select_by_visible_text("HomePhone")#根据文本selectsleep(1)driver.quit()selectmulti-selectionbox对于selectmulti-selectionbox,如果你需要选择一些选项,然后,注意清除之前选择的选项。示例应用程序fromseleniumimportwebdriverfromtimeimportsleepfromselenium.webdriver.support.uiimportSelectdriver=webdriver.Chrome()#打开浏览器driver.get("http://sahitest.com/demo/selectTest.htm")#跳转到测试页面sleep(1)select_element=Select(driver.find_element_by_id("s4Id"))#创建Select对象select_element.deselect_all()select_element.select_by_value("o1val")#selectbyvaluesleep(1)select_element.select_by_index(4)#Selectbyindex(从1开始)sleep(1)select_element.select_by_visible_text("o2")#Selectbytextsleep(1)#打印select_element.options中option的所有options的text:print(option.text)sleep(2)driver.quit()总结