Selenium 提供了Select 包,让我们方便的操作下拉列表
一、先来看下下拉列表Select 的元素属性
二、对下拉列表操作步骤
1、首先需要从selenium导入select的方法:from selenium.webdriver.support.ui import Select,注意S大写
2、使用select方法前,先实例化:s1 = Select(self.driver.find_element_by_id('s1Id'))
3、可以通过index、value、visible_text三种方法操作
select_by_index(0) 从0开始
select_by_value() value是属性值
select_by_visible_text('Fax') visible_text是下拉列表看到的值
三、通过pycharm 来看下select,都提供了什么方法和属性
四、实例
from selenium import webdriver from time import sleep from selenium.webdriver.support.ui import Select driver = webdriver.Chrome() driver.get('http://sahitest.com/demo/selectTest.htm') ele = driver.find_element_by_id('s1') s1 = Select(ele) s1.select_by_index(1) #通过index选中第一个选项 sleep(2) s1.select_by_value('47') #通过value=47选中 cellphone sleep(2) s1.select_by_visible_text('Fax') #通过visible_text选中Fax sleep(2) print('all_selected_options: {}'.format(s1.all_selected_options)) #打印所有被选中的项 print('first_selected_options: {}'.format(s1.first_selected_option)) #打印第一个被选中的项 print('s1 is multiple: {}'.format(s1.is_multiple)) #这个select 是单选还是多选 print("ele text: {}".format(ele.text)) #显示所有下拉列表的选项visible text print("ele attribute value: {}".format(ele.get_attribute('value'))) #显示选中的项的value属性值 driver.quit()运行结果:
C:\Python36\python.exe E:/python/test1/day1/test8.py
all_selected_options: [<selenium.webdriver.remote.webelement.WebElement (session="e9b5ad6c30ce2ff13bfa5f2469f3809f", element="0.6994605324118583-6")>]
first_selected_options: <selenium.webdriver.remote.webelement.WebElement (session="e9b5ad6c30ce2ff13bfa5f2469f3809f", element="0.6994605324118583-6")>
s1 is multiple: None
ele text: --SELECT--
Business Phone
Cell Phone
Email
Fax
Home Phone
Mail
ele attribute value: 49
小结:
(1)掌握操作select 下拉列表的步骤
(2)注意value和visible_text的区别
(3)根据不同的目的,选择不同的操作方式(请看这篇文章:http://blog.csdn.net/duzilonglove/article/details/78054104)
另外推荐一篇经典博文:http://blog.csdn.net/huilan_same/article/details/52246012