Selenium操作下拉列表


DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<form action="javascript:alert('test')">

    province:
    <select name="province" id="province">
        <option value="bj">Beijingoption>
        <option value="tj">Tianjinoption>
        <option value="sh">Shanghaioption>
    select>
form>


body>
html>
from selenium import webdriver
from selenium.webdriver.support.select import Select

from time import sleep
import os

class Testcase(object):
    def __init__(self):
        self.driver = webdriver.Chrome()
        path  = os.getcwd()
        file_name = os.path.join(path, "study03.html")
        self.driver.maximize_window()
        self.driver.get(file_name)

    def test01(self):
        se = self.driver.find_element_by_name("province")
        select = Select(se)
        # 索引位置
        select.select_by_index(2)
        sleep(2)
        # 取value
        select.select_by_value("bj")
        sleep(2)
        # 取文本
        select.select_by_visible_text("Tianjin")
        sleep(2)
        self.driver.quit()


if __name__ == '__main__':
    case = Testcase()
    case.test01()

勾选多个

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<form action="javascript:alert('test')">

    province:
    <select name="province" id="province" multiple>
        <option value="bj">Beijingoption>
        <option value="tj">Tianjinoption>
        <option value="sh">Shanghaioption>
    select>
form>


body>
html>
# selenium操作下拉列表

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

from time import sleep
import os

class Testcase(object):
    def __init__(self):
        self.driver = webdriver.Chrome()
        path  = os.getcwd()
        file_name = os.path.join(path, "study03.html")
        self.driver.maximize_window()
        self.driver.get(file_name)

    def test01(self):
        se = self.driver.find_element_by_name("province")
        # 实例化
        select = Select(se)
        # 索引位置
        select.select_by_index(2)
        sleep(2)
        # 取value
        select.select_by_value("bj")
        sleep(2)
        # 取文本
        select.select_by_visible_text("Tianjin")
        sleep(2)
        self.driver.quit()

    def test02(self):
        se = self.driver.find_element_by_name("province")
        select = Select(se)
        for i in range(3):
            select.select_by_index(i)
            sleep(1)
        sleep(2)

        # 所有都反选
        select.deselect_all()
        sleep(2)
        self.driver.quit()

    def test03(self):
        se = self.driver.find_element_by_name("province")
        select = Select(se)

        # select.options 所有选项
        for option in select.options:
            print(option.text)

        self.driver.quit()


if __name__ == '__main__':

    case = Testcase()
    case.test03()