在使用options方法來獲取下拉列表值童社,無需選中下拉列表
#option 查詢所有選項
def test_selectoption(self):
se = self.driver.find_element(By.ID, 'provies')
# 導(dǎo)入方法快捷鍵 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扰楼,說明是使用姿勢不對,我們來看一下源碼是如何實現(xiàn)的
#源碼實現(xiàn)如下
@property
def first_selected_option(self):
-------------------------------------------------重點關(guān)注的分割線 --------------------------------------------------------
"""The first selected option in this select tag (or the currently selected option in a normal select)"""
可以看到這里進行了特別說明美浦,這個方法的兩個使用場景分別是
1.多選時第一個選中的選項
2.單選時當(dāng)前選中的選項
-------------------------------------------------重點關(guān)注的分割線---------------------------------------------------------
for opt in self.options:
if opt.is_selected():
return opt
raise NoSuchElementException("No options are selected")
因此我們想要使用first_selected_option就必須對元素進行選中操作
以下為多選的完善代碼
#使用循環(huán)時弦赖,對全部選項進行選擇
for i in range(3):
select.select_by_index(i)
sleep(1)
sleep(3)
#打印多選時第一個選項值
print(select.first_selected_option.text)
以下為單選的完善代碼 ,兩個值最終打印結(jié)果都是jiaduoduo
場景一、
#先使用select中的選中方法
select.select_by_index(1)
select.select_by_value('jiaduoduo')
#調(diào)用first_selected_option就能獲取當(dāng)前下拉框選中值啦
print(select.first_selected_option.text)
sleep(2)
場景二浦辨、
"""
當(dāng)循環(huán)中選中多個時
first_selected_option方法取的是退出循環(huán)時當(dāng)前選中的值
也就是value對應(yīng)為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)