在使用options方法来获取下拉列表值,无需选中下拉列表
#option 查询所有选项
def test_selectoption(self):
se = self.driver.find_element(By.ID, 'provies')
# 导入方法快捷键 alt+enter,补全全部格式 tab键
select = Select(se)
#打印所有选项的text
for option in select.options:
print(option.text)
sleep(2)
使用first_selected_option方法来获取下拉列表中的第一个值,未选中值时,报错Message: No options are selected
...
print(select.first_selected_option.text)
sleep(2)
...
报错信息如下:
raise NoSuchElementException("No options are selected")
selenium.common.exceptions.NoSuchElementException: Message: No options are selected
#翻译成中文就是未选择任何选项
这个报错是提示未查询到options,说明是使用姿势不对,我们来看一下源码是如何实现的
#源码实现如下
@property
def first_selected_option(self):
-------------------------------------------------重点关注的分割线 --------------------------------------------------------
"""The first selected option in this select tag (or the currently selected option in a normal select)"""
可以看到这里进行了特别说明,这个方法的两个使用场景分别是
1.多选时第一个选中的选项
2.单选时当前选中的选项
-------------------------------------------------重点关注的分割线---------------------------------------------------------
for opt in self.options:
if opt.is_selected():
return opt
raise NoSuchElementException("No options are selected")
因此我们想要使用first_selected_option就必须对元素进行选中操作
以下为多选的完善代码
#使用循环时,对全部选项进行选择
for i in range(3):
select.select_by_index(i)
sleep(1)
sleep(3)
#打印多选时第一个选项值
print(select.first_selected_option.text)
以下为单选的完善代码 ,两个值最终打印结果都是jiaduoduo
场景一、
#先使用select中的选中方法
select.select_by_index(1)
select.select_by_value('jiaduoduo')
#调用first_selected_option就能获取当前下拉框选中值啦
print(select.first_selected_option.text)
sleep(2)
场景二、
"""
当循环中选中多个时
first_selected_option方法取的是退出循环时当前选中的值
也就是value对应为jiaduoduo
"""
for option in select.options:
select.select_by_index(2)
sleep(2)
select.select_by_value('jiaduoduo')
sleep(2)
print(select.first_selected_option.text)