selenium自动化元素定位之下拉列表框

目录

一、查看被测应用元素信息

二、Select的下拉框怎么定位

其思路也是获取下拉的选项框,循环遍历寻找匹配的index,找到便设置成选中属性

三、非select的下拉框如何定位?


 在编写webUI自动化过程中,有些元素的定位,不能直接通过id、name等快速定位到。这些特殊的元素定位就需要我们了解和学习解决方案,例如下拉框、radio/checkbox等。本文一起来了解一下,下拉列表框该定位。

一、查看被测应用元素信息

被测应用如图,禅道的添加用户页面,有一个部门的选项,是下拉列表框,这种类型的如何定位呢?

二、Select的下拉框怎么定位

 F12打开控制,点击具体的元素,看到它的属性

select标签,name和id都是'dept' ,试试如下定位fang

s1= Select(driver.find_element(By.ID,'dept'))
s1.selec_by_index(1)

也可以封装成一个方法

    def select_by_index(self, By, by_value, index):
        """
        根据index进行选择
        by      定位方式
        by_value   定位值
        index      下标
        """
        select = self.driver.find_element(By, by_value)
        depts = Select(select)
        depts.select_by_index(index)

其中select_by_index是selenium自有方法源码,可直接调用,如下是源码信息

    
def select_by_index(self, index):
        """Select the option at the given index. This is done by examining the
        "index" attribute of an element, and not merely by counting.

        :Args:
         - index - The option at this index will be selected

        throws NoSuchElementException If there is no option with specified index in SELECT
        """
        match = str(index)
        for opt in self.options:
            if opt.get_attribute("index") == match:
                self._set_selected(opt)
                return
        raise NoSuchElementException(f"Could not locate element with index {index}")

其思路也是获取下拉的选项框,循环遍历寻找匹配的index,找到便设置成选中属性

三、非select的下拉框如何定位?

实际情况,有用input标签的下拉框功能,怎么定位呢?如下图

只能通过模拟人手动点的方式触发事件

非select的下拉框可以通过以下方式抓取元素:

  1. 使用click()方法模拟用户点击下拉框,展开下拉选项。
  2. 使用find_elements_by_xpath()方法定位所有下拉选项的元素并存储到一个列表中。
  3. 遍历下拉选项列表,找到目标选项,并使用click()方法点击它。
  4. 如果需要输入内容,可以获取下拉框的input元素进行操作。

示例代码:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")

# 定位下拉框并点击展开
dropdown = driver.find_element_by_xpath('//input[@name="wd"]')
dropdown.click()

# 定位下拉选项并点击目标选项
options = driver.find_elements_by_xpath('//ul[@class="sug"]/li')
for option in options:
    if option.text == "Selenium":
        option.click()
        break

# 获取下拉框的input元素并输入内容(可选)
input_box = driver.find_element_by_xpath('//input[@name="wd"]')
input_box.send_keys("使用Selenium进行自动化测试")

其实也是仿写了上面selenium的select_by_index 思路循环遍历,只是先要通过click方法触发一下options的展示。

四、思考

我们在学习selenium UI自动化过程中,可以多去看源码,看看官方的解决思路是怎么样的,多看多实践,有些也可以为我所用。

猜你喜欢

转载自blog.csdn.net/michelle_li08/article/details/131502972