selenium操作下拉列表

1.导入(import)

from selenium.webdriver.support.ui import Select

# 或者直接从select导入

# from selenium.webdriver.support.select import Select

那么如果我们要定位第三个option,那么我们可以使用如下方法:

 

Select(driver.find_element_by_id("id_language")).select_by_value('en')

用Select来定位到select标签,而后再通过value来定位到第三个option,

当然Select类中包含几个用于定位的option的方法,如下:

options(self):

 此函数返回一个属于此select标签的option列表,不常用;

all_selected_options(self):

 此函数返回一个全部选择了的option的列表,不常用;

first_selected_option(self):

 此函数返回第一个或者当前被选中的option元素,不常用;

select_by_value(self, value):

 以传入的value属性值来进行匹配,并选择;

select_by_index(self, index):

 以传入的index属性值来查找匹配的元素并选择;

select_by_visible_text(self, text)

 选择所有有文本显示的option元素,如<option value="foo">Bar</option>;

deselect_all(self):

 将所有选择清除;

deselect_by_value(self, value):

 以传入的value属性值来查找该option并取消选择;

deselect_by_index(self, index):

 以传入的index属性值来查找匹配的元素并取消选择;

deselect_by_visible_text(self, text):

 以传入的text文本值来查找匹配的元素并取消选择;

 

2.选择(select)

Select类提供了三种选择某一选项的方法:

select_by_index(index)
select_by_value(value)
select_by_visible_text(text)



针对于示例网站中的第一个select框:

<select id="s1Id">
<option></option>
<option value="o1" id="id1">o1</option>
<option value="o2" id="id2">o2</option>
<option value="o3" id="id3">o3</option>
</select>

from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Firefox() driver.get('http://sahitest.com/demo/selectTest.htm')
s1 = Select(driver.find_element_by_id('s1Id'))

# 实例化
Select s1.select_by_index(1)

# 选择第二项选项:
o1 s1.select_by_value("o2")

# 选择value="o2"的项
s1.select_by_visible_text("o3")
# 选择text="o3"的值,即在下拉时我们可以看到的文本
driver.quit()


想查看一个select所有的选项

...

s1 = Select(driver.find_element_by_id('s1Id'))

for select in s1.options:
    print select.text

...



 想查看我已选中的选项

...

s4 = Select(driver.find_element_by_id('s4Id'))

s4.select_by_index(1)
s4.select_by_value("o2val")
s4.select_by_visible_text("With spaces")
s4.select_by_visilbe_text("    With nbsp")

for select in s4.all_selected_options:
    print select.text

...


 想要查看选择框的默认值,或者我以及选中的值

...

s2 = Select(driver.find_element_by_id('s2Id'))

print s2.first_selected_option.text

s2.select_by_value("o2")
print s2.first_selected_option.text

...

详细内容可以参考:http://blog.csdn.net/huilan_same/article/details/52246012
 
posted @ 2016-11-28 17:23  kakaok  阅读(109)  评论(0)    收藏  举报