学习Python中Selenium模块的基本用法(19:操作下拉框)

  Selenium模块的Select类专门用于处理HTML的select下拉框元素,它提供了简洁的API来操作单选框和复选框,支持通过多种方式选择选项,极大简化了Web自动化测试中对下拉框的操作。
  Select类相关函数或属性如下表所示:

序号 名称 说明
1 Select 基于select元素创建Select对象,下面行中的属性或函数都属于Select对象
2 options 属性,获取Select对象的所用选项
3 all_selected_options 属性,获取Select对象的所有选中选项
4 select_by_visible_text 函数,根据选项显示值选择选项
5 select_by_value 函数,根据选项内部值(value)选择选项
6 select_by_index 函数,根据选项索引值选择选项
7 deselect_by_value 函数,根据选项内部值取消选择选项,仅针对复选类型的下拉选择框

  使用DeepSeek生成包含单选框或复选框的测试页面,基于上述属性和函数编写测试程序,主要包括设置单选、设置多选、取消多选、获取选中项等方面,测试代码及测试效果如下所示:

python 复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
import time

driver = webdriver.Chrome()
driver.get("file:///E:/MyPrograms/HTML/testselect.html")

time.sleep(3)

single_select_element = driver.find_element(By.ID, 'single-select')
single_select= Select(single_select_element)
single_select.select_by_visible_text('中文 (Chinese)')

for option in single_select.all_selected_options:
    print(option.text)

time.sleep(1)

multi_select_element = driver.find_element(By.ID, 'multi-select')
multi_select= Select(multi_select_element)
multi_select.select_by_visible_text('中文 (Chinese)')
multi_select.select_by_index ('3')
multi_select.select_by_value('fr')

time.sleep(1)

multi_select.deselect_by_value('fr')

for option in multi_select.all_selected_options:
    print(option.text)

参考文献:

1https://www.selenium.dev/zh-cn/

2https://www.selenium.dev/zh-cn/documentation/webdriver/getting_started/

3https://blog.csdn.net/kk_lzvvkpj/article/details/148610502

4https://registry.npmmirror.com/binary.html?path=chromedriver/

5https://chromedriver.chromium.org/

相关推荐
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技2 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时2 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊2 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1232 天前
2026年第38周GitHub趋势周报
python·科技·github
IZero072 天前
Jev 与 Laya
python·语言模型