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

相关推荐
Franklin11 分钟前
如何解决git HEAD detached 分离头指针问题
git·python·pycharm
deephub20 分钟前
Anthropic 开源 Bloom:基于 LLM 的自动化行为评估框架
人工智能·python·自动化·大语言模型·行为评估
万兴丶24 分钟前
批量转换音频格式工具
python
大学就业之家27 分钟前
智能选岗的陷阱与应对策略
python
chenshi178128 分钟前
安全合规:使用 RPA 批量发布时,如何规避平台封禁风险,实现长效稳定的投喂?
python
superman超哥40 分钟前
仓颉性能瓶颈定位方法深度解析
c语言·开发语言·c++·python·仓颉
岁岁的O泡奶1 小时前
NSSCTF_crypto_[SWPU 2020]happy
经验分享·python·算法·密码学
武汉唯众智创1 小时前
“物联网 Python 开发教程”课程教学解决方案
开发语言·python·物联网·物联网技术·物联网 python 开发·python 开发
时光Autistic1 小时前
【搭建教程】腾讯混元3D模型部署
开发语言·python·3d·github
前端程序猿之路1 小时前
AI大模型应用之-RAG 全流程
人工智能·python·gpt·语言模型·aigc·mybatis·ai编程