学习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)

参考文献:

1\]https://www.selenium.dev/zh-cn/ \[2\]https://www.selenium.dev/zh-cn/documentation/webdriver/getting_started/ \[3\]https://blog.csdn.net/kk_lzvvkpj/article/details/148610502 \[4\]https://registry.npmmirror.com/binary.html?path=chromedriver/ \[5\]https://chromedriver.chromium.org/

相关推荐
IVEN_17 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang18 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮19 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling19 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮1 天前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽1 天前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健2 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞2 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers