[Selenium][Notes]Day3:3️⃣使用select类操作dropdown list

306 阅读1分钟

常用方法:

#方法/属性方法/属性描述
1select_by_value()根据值选择
2select_by_index()根据索引选择
3select_by_visible_text()根据文本选择
4deselect_by_value()根据值反选
5deselect_by_index()根据索引反选
6deselect_by_visible_text()根据文本反选
7deselect_all反选所有
8options所有选项
9all_selected_options所有选中选项
10first_selected_options第一个选择选项
注意事项:
  • index索引是从“0”开始;
  • value是option标签的一个属性值,并不是显示在下拉框中的值;
  • visible_text是在option标签中间的值,是显示在下拉框的值;

实例Code:

Python
from selenium import webdriver
from time import sleep
import os

from selenium.webdriver.support.select import Select


class TestCase(object):
    def __init__(self):
        self.driver = webdriver.Chrome()
        path = os.path.dirname(os.path.abspath(__file__))  # 当前文件所在目录路径
        # file协议拼接
        file_path = 'file:///' + path + '/forms3.html'
        # 访问本地html
        self.driver.get(file_path)

    def test_select(self):
        # 找到下拉菜单元素
        province = self.driver.find_element_by_id('province')
        select = Select(province)  # 实例化select
        # 根据索引选择list中第三个:Shanghai
        select.select_by_index(2)
        sleep(2)
        # 根据值选择Beijing
        select.select_by_value('bj')
        sleep(2)
        # 根据文本选择Tianjin
        select.select_by_visible_text('Tianjin')
        sleep(2)
        self.driver.quit()
        print('Pass')

    def test_multiple_select(self):
        # 找到下拉菜单元素
        hobby = self.driver.find_element_by_id('hobby')
        select = Select(hobby)  # 实例化select
        # for循环全选
        for i in range(3):
            select.select_by_index(i)
            sleep(1)
        sleep(2)
        # 全部反选
        select.deselect_all()
        sleep(2)
        self.driver.quit()
        print('Pass')

    def test_option(self):
        province = self.driver.find_element_by_id('province')
        select = Select(province)
        # 返回select元素所有的options
        for option in select.options:
            print(option.text)
        self.driver.quit()
        print('Pass')

if __name__ == '__main__':
    case = TestCase()
    # case.test_select()
    # case.test_multiple_select()
    case.test_option()
HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="javascript:alert('Hello')">
    <header>Province</header>
    province:
    <select name="province" id="province">
        <option value="bj">Beijing</option>
        <option value="tj">Tianjin</option>
        <option value="sh">Shanghai</option>
        <option value="cq">Chongqing</option>
    </select>
<hr>
    <header>Hobby</header>
    Hobby:
    <select name="hobby" id="hobby" multiple>
        <option value="swim">Swimming</option>
        <option value="run">Running</option>
        <option value="walk">Walking</option>
    </select>

</form>
</body>
</html>