标签:div ble __file__ mil support 初始化 loading 使用 find
用法:
1、先导入Select类
from selenium.webdriver.support.select import Select
2、实例化,通过源码可知初始化对象的时候需要传入下拉框元素对象:
3、示例代码
#form2.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="javascript:alert(‘test‘)"> 省份: <select id="province" > <option value="bj">北京市</option> <option value="tj">天津市</option> <option value="sc">四川省</option> <option value="sd">山东省</option> <option value="hn">河南省</option> </select> </form> </body> </html>
测试代码
from selenium import webdriver import os from time import sleep from selenium.webdriver.support.select import Select class TestCase(): def __init__(self): self.driver = webdriver.Chrome() html_path = os.path.dirname(os.path.abspath(__file__)) # 本地的html文件地址拼接 file_path = "file:///" + html_path + ‘/form2.html‘ self.driver.get(file_path) self.driver.maximize_window() se = self.driver.find_element_by_id(‘province‘) self.select = Select(se) def test_single_select(self): """单选下拉框的测试""" # 根据值选择 self.select.select_by_value(‘tj‘) sleep(2) # 根据索引选择 self.select.select_by_index(0) sleep(2) # 根据文本选择 self.select.select_by_visible_text(‘四川省‘) sleep(2) self.driver.quit() def test_multiple_slect(self): """多选下拉框的测试,需要在表单元素中添加multiple参数""" # 获取所有选项标签 options = self.select.options # 遍历选中所有标签 for option in options: option.click() sleep(2) selected_options = self.select.all_selected_options print(‘所有选中的选项:‘, selected_options) first_selected_option = self.select.first_selected_option print(‘第一个选中的选项值:‘, first_selected_option.get_attribute(‘value‘)) # 根据值反选 self.select.deselect_by_value(‘bj‘) sleep(2) # 根据索引反选 self.select.deselect_by_index(3) sleep(2) # 根据文本反选 self.select.deselect_by_visible_text(‘河南省‘) sleep(2) # 反选所有 self.select.deselect_all() sleep(2) self.driver.quit() if __name__ == ‘__main__‘: case = TestCase() # case.test_single_select() case.test_multiple_slect()
python+selenium2自动化---使用Select类实现下拉列表的定位
标签:div ble __file__ mil support 初始化 loading 使用 find
原文地址:https://www.cnblogs.com/Xiaojiangzi/p/13375770.html