selenium基础篇:对select类定位操作

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_path = 'file:///'+path+'/formDemo.html' # 字符串拼接,获取所需文件路径
        print('文件地址是:'+file_path)
        self.driver.get(file_path)
    def test_checkbox(self):
        sleep(2)
        swimming = self.driver.find_element_by_name('swimming')
        if not swimming.is_selected():
            swimming.click()
        reading = self.driver.find_element_by_name('reading')
        if not reading.is_selected():
            reading.click()
        sleep(3)
        swimming.click()
        reading.click()
        sleep(5)
        self.driver.quit()
    #单选
    def test_radio(self):
        lst = self.driver.find_elements_by_name('gender')
        lst[0].click()
        print(lst[1])
    #选择框单选
    def test_select(self):
        se = self.driver.find_element_by_id('province')
        select = Select(se)
        select.select_by_index(2)  #根据下标
        sleep(2)
        select.select_by_value('bj')#根据值
        sleep(2)
        select.select_by_visible_text('Tianjin')#根据可视化文本
        sleep(2)
        self.driver.quit()
    #选择框多选
    def test_select_mult(self):
        se = self.driver.find_element_by_name('province')
        select = Select(se)
        for i in range(3):
            select.select_by_index(i)
            sleep(2)
        sleep(3)
        select.deselect_all()
        sleep(2)
        self.driver.quit()
if __name__ == '__main__':
    case = TestCase()
    #case.test_checkbox()
    #case.test_radio()
    #case.test_select()
    case.test_select_mult()
原文地址:https://www.cnblogs.com/c-jw/p/13806686.html