selenium:Select类操作复选框和下拉框(7)

复选框/下拉框操作的Select类

主要使用selinium中的类Select来模拟选择网页上的下拉框或者复选框中的内容,使用前先导入

from selenium.webdriver.support.ui import Select

主要方法如下:

|--------------------------|-----------------|
| 函数 | 功能 |
| select_by_value | 根据复选框/下拉框的值选择 |
| select_by_index | 根据复选框/下拉框的索引选择 |
| select_by_visible_text | 根据复选框/下拉框文本描述选择 |
| deselect_by_value | 根据复选框/下拉框的值反选 |
| deselect_by_index | 根据复选框/下拉框的索引反选 |
| deselect_by_visible_text | 根据复选框/下拉框文本描述反选 |
| deselect_all | 反选所有值 |
| options | 返回所有选项 |
| all_selected_options | 返回所有选中的选项 |
| first_selected_option | 第一个选择的选项 |

我们自定义一个html文件,放一个多选框和下拉框方便测试

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/submit-path">
<label for="fruits">Choose your favorite fruit:</label>
<select id="fruits" name="fruits" multiple>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="banana">Banana</option>
<option value="grape">Grape</option>
</select>
</form>
<form action="/submit-path">
<label for="animals">Choose your favorite animal:</label>
<select id="animals" name="animals">
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="tiger">Tiger</option>
</select>
</form>
<input type="submit" value="提交" id="su" class="btn self-btn bg s_btn">
</body>
</html>

打开这个html页面如下:一个多选框和一个下拉框

示例:打开html文件,选择多选框内容和下拉框内容。

打开网页,并初始化Select类:

复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
driver = webdriver.Safari()
# 打开一个网页
driver.get("file:///Users/abc/Desktop/myhtml.html")
driver.maximize_window()
sleep(2)

#初始化Select类,传入水果多选框对应的元素位置
select_content1 = Select(driver.find_element(By.ID,'fruits'))

#初始化Select类,传入动物下拉框对应的元素位置
select_content2 = Select(driver.find_element(By.ID,'animals'))

使用select_by_value函数选择水果多选框第1个和第2个内容

复制代码
select_content1.select_by_value('apple')
select_content1.select_by_value('orange')

使用deselect_all函数去掉水果多选框的所有的选择

复制代码
select_content1.deselect_all()

使用select_by_index函数选择动物下拉框的第3个内容

复制代码
select_content2.select_by_index(2)

执行结果如视频所示:

多选框

共勉: 东汉·班固《汉书·枚乘传》:"泰山之管穿石,单极之绠断干。水非石之钻,索非木之锯,渐靡使之然也。"

-----指水滴不断地滴,可以滴穿石头;

-----比喻坚持不懈,集细微的力量也能成就难能的功劳。

----感谢读者的阅读和学习,谢谢大家。

相关推荐
XYN6115 分钟前
【嵌入式学习3】基于python的tcp客户端、服务器
服务器·开发语言·网络·笔记·python·学习·tcp/ip
一一代码23 分钟前
ide技术
ide·python
No0d1es29 分钟前
CCF GESP Python编程 三级认证真题 2025年3月
python·青少年编程·gesp·ccf·三级
JobDocLS38 分钟前
深度学习环境安装
python
二狗哈1 小时前
go游戏后端开发24:写完赢三张游戏
python·游戏·golang
明月看潮生1 小时前
青少年编程与数学 02-016 Python数据结构与算法 03课题、数组与链表
数据结构·python·青少年编程·编程与数学
niuniu_6662 小时前
针对 Python 3.7.0,以下是 Selenium 版本的兼容性建议和安装步骤
开发语言·chrome·python·selenium·测试工具
苏卫苏卫苏卫2 小时前
【Python】数据结构练习
开发语言·数据结构·笔记·python·numpy·pandas
benben0442 小时前
Unity3D仿星露谷物语开发34之单击Drop项目
游戏·ui·unity·游戏引擎
DexterLien2 小时前
Flask + Pear Admin Layui 快速开发管理后台
python·flask·layui