处理下拉列表,需要用到Selenium中的一个工具类Select,以下是常用方法/属性:
| 方法/属性 | 方法/属性描述 |
|---|---|
| select_by_value() | 根据值选择 |
| select_by_index() | 根据索引选择 |
| select_by_visible_text | 根据文本选择 |
| deselect_by_value | 根据值反选 |
| deselect_by_index | 根据索引反选 |
| deselect_by_visible_text | 根据文本反选 |
| deselect_all | 反选所有 |
| all_selected_options | 所有选中选项 |
| first_selected_option | 第一个选择选项 |
下面是一个有下拉框(单选)的页面
Title
from selenium import webdriver
from time import sleep
import os
from selenium.webdriver.support.select import Select
class TestCase():
def __init__(self):
self.driver = webdriver.Chrome()
path = os.path.dirname(os.path.abspath(__file__))
file_path = 'file:///'+path+'/forms4.html'
self.driver.get(file_path)
#下拉框单选
def test_select(self):
se = self.driver.find_element_by_id('province')
select = Select(se)
select.select_by_index(1)
sleep(2)
select.select_by_value('tj')
sleep(2)
select.select_by_visible_text('湖北')
sleep(2)
self.driver.quit()
if __name__ == '__main__':
case = TestCase()
case.test_select()
下面是一个有下拉框(多选)的页面
Title
from selenium import webdriver
from time import sleep
import os
from selenium.webdriver.support.select import Select
class TestCase():
def __init__(self):
self.driver = webdriver.Chrome()
path = os.path.dirname(os.path.abspath(__file__))
file_path = 'file:///'+path+'/forms4.html'
self.driver.get(file_path)
#下拉框多选
def test_select_all(self):
se = self.driver.find_element_by_id('province')
select = Select(se)
for i in range(4):
select.select_by_index(i)
sleep(1)
sleep(3)
self.driver.quit()
if __name__ == '__main__':
case = TestCase()
case.test_select_all()



