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)

执行结果如视频所示:

多选框

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

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

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

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

相关推荐
布林模型30 分钟前
缠论工具czsc快速使用入门(二)
python·缠论·快速入门·czsc
紧固视界36 分钟前
机械臂装配自动化推动紧固件设计革新
运维·自动化
邂逅you44 分钟前
用python操作mysql之pymysql库基本操作
数据库·python·mysql
啊森要自信1 小时前
【GUI自动化测试】YAML 配置文件应用:从语法解析到 Python 读写
android·python·缓存·pytest·pip·dash
合作小小程序员小小店1 小时前
web开发,学院培养计划系统,基于Python,FlaskWeb,Mysql数据库
后端·python·mysql·django·web app
渣渣盟1 小时前
解密NLP:从入门到精通
人工智能·python·nlp
老程序员刘飞1 小时前
注册 区块链节点
python
KAIWEILIUCC1 小时前
Python抽象基类(abc.ABC)介绍
python
傻啦嘿哟1 小时前
用Selenium模拟登录淘宝并采集商品信息:从基础到实战
selenium·测试工具
独行soc2 小时前
2025年渗透测试面试题总结-106(题目+回答)
网络·python·安全·web安全·adb·渗透测试·安全狮