当前位置: 首页> 教育> 幼教 > selenium中,如何使用选择框

selenium中,如何使用选择框

时间:2025/7/9 17:07:05来源:https://blog.csdn.net/Ataoker/article/details/139506718 浏览次数:0次

html5 

一个多选下拉框,没有默认选

一个单选下拉狂,默认“张桐桐”

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>选择框</title>
</head>
<body><label for="multiSelect">下拉(多选:</label><select id="multiSelect" multiple><option value="option1">选项1</option><option value="option2">选项2</option><option value="option3">选项3</option></select><br><br><label for="singleSelect">下拉(单选:</label><select id="singleSelect" ><option value="boy" >男</option><option value="girl">女</option><option value="tongtong" selected="selected">张桐桐</option></select>
</body>
</html>

方式1: 传统点

直接定位到选项,进行click ,  或者定位到选项, 用send_keys

from selenium import webdriver
import time# 创建浏览器驱动对象
from selenium.webdriver.common.by import Bydriver = webdriver.Chrome()            # 参数写浏览器驱动文件的路径,若配置到环境变量就不用写了
# 访问网址
driver.get("E:\django\接口准备1\选择框.html")# (多选框)直接定位到选项元素,然后点击
"""
两个点了都会选上
"""
driver.find_element(By.CSS_SELECTOR,'option[value="option1"]').click()
driver.find_element(By.CSS_SELECTOR,'option[value="option3"]').click()# (单选框)
"""
点了一个,之前的会取消掉
"""
time.sleep(2)
driver.find_element(By.CSS_SELECTOR,'option[value="girl"]').click()
time.sleep(2)driver.find_element(By.CSS_SELECTOR,'#singleSelect').send_keys("男")

方式2:实例化一个select 对象来定位

相比上面, 他不是一个点击行为,而是一个选择行为,比如默认选了 ,“张桐桐”, 通过方式2的方法再选男,他还是 "张桐桐"

from selenium import webdriver
import time# 创建浏览器驱动对象
from selenium.webdriver.common.by import Bydriver = webdriver.Chrome()            # 参数写浏览器驱动文件的路径,若配置到环境变量就不用写了
# 访问网址
driver.get("E:\django\接口准备1\选择框.html")from selenium.webdriver.support.select import Select# 实例化一个选择对象
selelct1 = Select(driver.find_element(By.CSS_SELECTOR,'#multiSelect'))selelct1.select_by_index(0)             # 方式1selelct1.select_by_value("option2")     # 方式2
time.sleep(1.5)
selelct1.select_by_visible_text("选项3")  # 方式3# 实例化一个选择对象 (下面的)
select2 = Select(driver.find_element(By.CSS_SELECTOR,'#singleSelect'))select2.select_by_index(0)      # 若換成2, 他就還是和默認保持不变selelct1.select_by_index(0)

关键字:selenium中,如何使用选择框

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: