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)

执行结果如视频所示:

多选框

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

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值