下拉列表

HTML里的下拉列表表示方式,一般来说分为两种情况

  • 传统下拉列表:标准的select标签下拉列表表示方式,下级是optio
  • 组装下拉列表:非select标记,比如li、div、input、img组装而成,界面上显示的效果也是看起来像是下拉列表的样子。

传统下拉列表(标准下拉列表)

Selenium19-下拉列表操作_下拉列表


两种操作方式,方式一是模拟手工的操作动作(先点击xx,等待,再点击xxx),方式二是使用下拉列表的专用操作类Select

组装下拉列表

Selenium19-下拉列表操作_排序规则_02

下拉列表测试方式

Selenium19-下拉列表操作_下拉列表_03

Select类
  • 对于select标记的下拉列表,selenium webdriver提供了专用Select来处理

    # 导入select类
    from selenium.webdriver.support.select import Select
    # 定位下拉列表:html里select标记的页面元素
    变量1 = driver.find_element(By....,...)
    # 封装select对象:调用构造方法,得到该类型的对象实例
    变量2 = Select(变量1) # 变量2数据类型是一个select
Select类里的操作方法

Selenium19-下拉列表操作_搜索_04

Select类里的属性

属性:可以通过Select对象实例直接获得这些属性的值

Selenium19-下拉列表操作_下拉列表_05

"""
打开ECshop前台首页
选择分类下拉列表里的耳机选项
输入搜索关键字 5
点击搜索
判断第二个排序规则下拉列表里当前选项文本,如果是倒序,就选择文本是正序的选项
判断第一个排序规则下拉列表里的当前选项文本,如果包含上架时间,就从所有选项中选择一个文本内包含价格的选项
"""
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select

driver = webdriver.Firefox() # 启动浏览器
driver.get('http://localhost/upload/index.php')
a = driver.find_element(By.ID,"category") # 定位分类的下拉列表
b = Select(a)
b.select_by_visible_text(' 耳机')# 注意参数必须是完整的选项文本(包含空格)
driver.find_element(By.ID,"keyword").send_keys('5') # 定位关键字文本框输入5
driver.find_element(By.NAME,"imageField").click() # 定位搜索按钮
sleep(3)
# 排序规则里第二个下拉列表
order1 = driver.find_element(By.NAME,'order')
s1 = Select(order1)
# 获得当前选项的文本
t1 = s1.first_selected_option.text
if t1=='倒叙':
s1.select_by_value("ASC") # 选择升序
# 排序规则第一个下拉列表
sort1 = driver.find_element(By.NAME,'sort')
s2 = Select(sort1)
t2 = s2.all_selected_options.text
if "上架时间" in t2:
for o in s2.options:#options属性值记录所有选项(由页面元素组成的列表)
t = o.text # 获得每个选项的文本
if "价格" in t:
s2.select_by_visible_text(t) # 选择文本里包含价格的选项
break
driver.quit()
Select类小结

使用select类之前需要

  • 导入Select类、定位html网页里select标记的元素、封装select对象

Select提供了三种选择方法

  • select_by_index(index) -- 通过选项的顺序,第一个为0
  • select_by_value("value") -- 通过value属性
  • select_by_visible_text("text")--通过选项可见文本

Select类提供了四种方法取消选择:只适合于有能多选的下拉列表

  • deselect_by_index(index)
  • deselect_by_value("value")
  • deselect_by_visible_text("text")
  • deselect_all()

Select提供了三个属性方法

  • options --提供所有的选项的列表,其中都是选项的WebElement元素
  • all_selected_options --提供所有被选中的选项的列表,其中也均为选项的WebElement元素
  • first_selected_option --提供第一个被选中的选项,也是下拉框的默认值

作者:暄总-tester