下拉框操作
流程
定位元素-初始化对象-操作(三种方式:索引,value值,元素文本。)
获取已选择的选项
获取所有可选择的选项
判断是否可以进行多选 不可多选不一定会返回false,可多选一定返回true
获取第一个选择的选项
取消所选择的项(仅适⽤于多选列表)四种方法:
多选框
# coding = utf-8
# Author:dan.zhang
# Date:2023/11/14
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
driver = webdriver.Chrome()
driver.get("file:///D:/WebAutoCode/testcase/下拉框示例.html")
driver.maximize_window()
# 点击触发多选
driver.find_element(By.XPATH,"//button").click()
# 定位多选元素
select_element = driver.find_element(By.ID,"multiSelect")
# 初始化对象
select_object = Select(select_element)
# 判断是否可以进行多选
check_selects = select_object.is_multiple
print("是否允许多选:",check_selects)
# 索引
select_object.select_by_index(2)
time.sleep(3)
# value
select_object.select_by_value("option1")
time.sleep(3)
# 文本
select_object.select_by_visible_text("选项2")
time.sleep(3)
# 获取已选择的元素
selected_options = select_object.all_selected_options
print(f"已选择{len(selected_options)}个选项")
# 获取所有可选择的选项
all_selects = select_object.options
print(f"有{len(all_selects)}选项可以选择")
# 获取第一个选择的选项
first_select = select_object.first_selected_option
print(f"第一个选择的选项:{first_select}")
driver.quit()
单选框
# coding = utf-8
# Author:dan.zhang
# Date:2023/11/5 21:53
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
driver = webdriver.Chrome()
driver.get("file:///D:/WebAutoCode/testcase/下拉框示例.html")
driver.maximize_window()
select_element = driver.find_element(By.NAME, "singleSelect")
select_object = Select(select_element)
# 索引
select_object.select_by_index(2)
# value
select_object.select_by_value("option1")
# 文本
select_object.select_by_visible_text("选项2")
# 获取已选择的选项
selected_option = select_object.all_selected_options
print("已选择的选项:", selected_option)
print(f"已经选择了{len(selected_option)}个选项")
# 获取所有可选择的选项
all_selects = select_object.options
print("所有可选择的选项", all_selects)
print(f"可选择的选项共{len(all_selects)}个")
# 获取第一个选择的选项
first_select = select_object.first_selected_option
print(f"第一个选择的选项:{first_select}")
time.sleep(3)
driver.quit()
定位元素 el
select_object = Select(el)
3+3+1+4
select_object.select_by_index()
by_value()
by_visible_text()
all_selected_options
options
first_selected_option
is_multiple
deselect_all()
deselect_by_index()
by_value()
by_visible_text()