1. 程式人生 > >12、Selenium + Python 實現 UI 自動化測試-操作下拉列表

12、Selenium + Python 實現 UI 自動化測試-操作下拉列表

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