Web automation: 6. Operation of selenium drop-down selection box - Select

When doing web automation testing, the drop-down box is definitely inevitable. Let’s briefly talk about its implementation

There are 2 ways to implement the front end of the drop-down selection box:

1. Original way

 <select> </select>  

2. Use js to control the display or hiding of options to achieve the same effect as the select tag

<div> </div> 

Implementation method of drop-down box selection

1. Conventional operation, applicable to the above two methods
First locate and click the selection box element; after the drop-down box options are displayed, then locate and click the option element.

2. The Select class is only applicable to the drop-down box implemented by the select tag.
The principle is actually the steps of conventional operations, but selenium provides the Select class, which is more convenient to encapsulate the code for use.

practise

I write a simple html file in python language, which is convenient for practice. The code is as follows:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>select选择框的操作</title>
</head>
<body>
    <h6>花测试  select选择框的操作</h6>
    <select id="test">
        <option value="hsl">何时了</option>
        <option value="qy">秋月</option>
        <option value="ch">春花</option>
    </select>
</body>
</html>

1. Routine operation

from selenium import webdriver

driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.maximize_window()
url = '根据实际填写:在本地打开上面的html文件,然后复制浏览器上的url粘贴过来'
driver.get(url)

# 常规通用法
select_cl = driver.find_element('id', 'test')
select_cl.click()
select_cl = driver.find_element('xpath', '//option[text()="秋月"]')
select_cl.click()

2. Use the Select class

from selenium import webdriver
from selenium.webdriver.support.select import Select

driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.maximize_window()
url = '根据实际填写:在本地打开上面的html文件,然后复制浏览器上的url粘贴过来'
driver.get(url)

select_cl = driver.find_element('id', 'test')   # 定位选择框元素
s = Select(select_cl)   # 初始化一个 select 对象

# 方法1:通过option选项中的 value 属性选中选项
s.select_by_value('qy')

# 方法2:通过索引选中选项
s.select_by_index(1)   # 从0开始

# 方法3:通过文本选中选项
s.select_by_visible_text('秋月')

Guess you like

Origin blog.csdn.net/weixin_48415452/article/details/120163959