Python自动化测试系列[v1.0.0][处理下拉菜单]

Selenium为选择下拉菜单中的选项提供了3中方法,接下来分别将这三种方法进行封装然后调用。

方法封装

from selenium.webdriver.support.select import Select
def select_by_index(self, element, index):
    """
    通过下拉菜单的索引,完成对选项的选择
    :param element:
    :param value:
    :return:
    """
    Select(element).select_by_index(index)
def select_by_value(self, element, value):
    """
    通过选项值,完成对选项的选择
    :param element:
    :param value:
    :return:
    """
    Select(element).select_by_value(value)
def select_by_text(self, element, text):
    """
    通过选项的文本,完成对选项的选择
    :param element:
    :param text:
    :return:
    """
    Select(element).select_by_visible_text(text)

方法调用

def test_select(self):
    chrome_driver = webdriver.Chrome()
    chrome_driver.get("http://www.baidu.com")
    chrome_driver.implicitly_wait(30)
    mouse = chrome_driver.find_element_by_link_text("设置")
    ActionChains(chrome_driver).move_to_element(mouse).perform()
    chrome_driver.find_element_by_link_text("搜索设置").click()
    time.sleep(5)
    chrome_driver.find_element_by_name("NR").click()
    time.sleep(5)
    select = chrome_driver.find_element_by_name("NR")
    Browser_Controller(chrome_driver).select_by_value(select, "20")
    time.sleep(5)
    Browser_Controller(chrome_driver).select_by_index(select, 1)
    time.sleep(5)
    Browser_Controller(chrome_driver).select_by_text(select, "每页显示50条")
    time.sleep(5)

方法扩展

实际上Selenium提供的处理下拉菜单选项的不止我们封装的三种方法,还有如下所示取消选项选择的方法

deselect_by_index(index)  # 根据索引取消选择
deselect_by_value(value)  # 根据value取消选择 
deselect_by_visible_text(text)  # 根据文本取消选择 
deselect_all()  # 取消所有选择

你可能感兴趣的:(Python自动化测试系列[v1.0.0][处理下拉菜单])