- 导入工具类 Select
from selenium.webdriver.support.select import Select
- 定位select的WebElement
ele = driver.find_element_by_id('demo')
- Select实例化
selectEle = Select(ele)
- 然后就可以调用Select的方法了
selectEle.select_by_value(str) | 根据value值选择 |
selectEle.select_by_index(n) | 根据索引值选择 |
selectEle.select_by_visible_text(str) | 根据文本选择 |
selectEle.deselect_by_value(str) | 根据value值反选 |
selectEle.deselect_by_index(n) | 根据索引值反选 |
selectEle.deselect_by_visible_text(str) | 根据文本反选 |
selectEle.deselect_all() | 清空已选择的选项 |
selectEle.options | 返回全部选项 |
selectEle.all_selected_options | 返回被选中的选项 |
selectEle.first_selected_option | 返回第一个被选中的选项 |
实例
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
with webdriver.Chrome() as driver:
driver.get("http://sahitest.com/demo/selectTest.htm")
driver.maximize_window()
time.sleep(3)
# 实例化select
contact = Select(driver.find_element(By.ID, 's1'))
# 获取所有选项
contact_list = contact .options
for option in contact_list:
print(option.text + ' 的value值是: ' + option.get_attribute('value'))
s1 = Select(driver.find_element(By.ID, 's1Id'))
# 根据value选择
s1.select_by_value('o2')
# all_selected_options的返回值类型是list
print('value=o2 - 当前选项:', s1.all_selected_options[0].text)
# 根据index选择
s1.select_by_index(3)
print('index=3 - 当前选项:', s1.all_selected_options[0].text)
# 根据text选择
s1.select_by_visible_text('o1')
print('text=o1 - 当前选项:', s1.all_selected_options[0].text)
s4 = Select(driver.find_element(By.ID, 's4Id'))
# 多选
s4.select_by_visible_text('o2')
s4.select_by_visible_text('o3')
print('多选:')
for option in s4.all_selected_options:
print(option.text)
print('第一个被选中的项:', s4.first_selected_option.text)
# 反选
s4.deselect_all()
time.sleep(5)
print('反选:')
for option in s4.all_selected_options:
print(option.text)
运行结果
--SELECT-- 的value值是: -1
Business Phone 的value值是: 46
Cell Phone 的value值是: 47
Email 的value值是: 48
Fax 的value值是: 49
Home Phone 的value值是: 51
Mail 的value值是: 50
value=o2 - 当前选项: o2
index=3 - 当前选项: o3
text=o1 - 当前选项: o1
多选:
o2
o3
第一个被选中的项: o2
反选: