selenium中的一个工具类select主要用于处理下拉列表,常用的方法如下:
在这里,我们使用了和下面python文件同目录的form3.html,代码如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<form>
provide:
<select name="provise" id="provise">
<option value='bj'>BeiJing</option>
<option value='tj'>TianJin</option>
<option value='bj'>ShangHai</option>
</select>
</form>
</body>
</html>
1.单值选择
from selenium import webdriver
from time import sleep
import os
from selenium.webdriver.support.select import Select
class TestSelect01(object):
def __init__(self):
self.driver = webdriver.Chrome()
path = os.path.dirname(os.path.abspath(__file__)) #获取当前文件的目录
file_path = 'file:///' + path + '/form3.html'
self.driver.get(file_path) #运行form3.html
def test_select01(self):
se = self.driver.find_element_by_id('provise')
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()
if __name__ == '__main__':
case = TestSelect01()
case.test_select01()
2.多值选择
将form3.html中select标签改为如下所示便可支持多选
<select name="provise" id="provise" multiple>
from selenium import webdriver
from time import sleep
import os
from selenium.webdriver.support.select import Select
class TestSelect01(object):
def __init__(self):
self.driver = webdriver.Chrome()
path = os.path.dirname(os.path.abspath(__file__)) #获取当前文件的目录
file_path = 'file:///' + path + '/form3.html'
self.driver.get(file_path) #运行form3.html
def test_select02(self):
se = self.driver.find_element_by_id('provise')
for i in range(3):
select.select_by_index(i) #需要设置html中的下拉列表能支持多选
sleep(1)
sleep(3)
self.driver.quit()
if __name__ == '__main__':
case = TestSelect01()
case.test_select02()
3.反选
以deselect的开头的方法都可支持反选,在2中全选的情况下,全部反选,代码如下:
from selenium import webdriver
from time import sleep
import os
from selenium.webdriver.support.select import Select
class TestSelect01(object):
def __init__(self):
self.driver = webdriver.Chrome()
path = os.path.dirname(os.path.abspath(__file__)) #获取当前文件的目录
file_path = 'file:///' + path + '/form3.html'
self.driver.get(file_path) #运行form3.html
def test_select02(self):
se = self.driver.find_element_by_id('provise')
for i in range(3):
select.select_by_index(i) #需要设置html中的下拉列表能支持多选
sleep(1)
sleep(3)
select.deselect_all()
sleep(3)
self.driver.quit()
if __name__ == '__main__':
case = TestSelect01()
case.test_select02()
4.打印所有选项
可以使用Select类的属性options,代码如下:
from selenium import webdriver
from time import sleep
import os
from selenium.webdriver.support.select import Select
class TestSelect01(object):
def __init__(self):
self.driver = webdriver.Chrome()
path = os.path.dirname(os.path.abspath(__file__)) #获取当前文件的目录
file_path = 'file:///' + path + '/form3.html'
self.driver.get(file_path) #运行form3.html
def test_select03(self):
se = self.driver.find_element_by_id('provise')
for option in select.options:
print(option.text)
self.driver.quit()
if __name__ == '__main__':
case = TestSelect01()
case.test_select03()