代码如下:
前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="javascript:alert('test')">
provide:
<select name="provise" id="provise">
<option value="bj">BeiJing</option>
<option value="sh">ShangHai</option>
<option value="zz">ZhengZhou</option>
</select>
</form>
</body>
</html>
操作下拉框代码:
from selenium import webdriver
from time import sleep
from selenium.webdriver.support.select import Select
import os
class testcase(object):
def __init__(self):
self.driver=webdriver.Chrome()
# 获取绝对路径地址
patch = os.path.dirname(os.path.abspath(__file__))
print(patch)
# 拼接地址
file_patch = 'file:///' + patch + '/forms3.html'
print(file_patch)
self.driver.get(file_patch)
def test_select(self):
"""下拉框选择想要的数据"""
se= self.driver.find_element_by_id('provise')
select=Select(se)
select.select_by_index(2)
sleep(2)
select.select_by_value('bj')
sleep(2)
select.select_by_visible_text('ShangHai')
sleep(2)
self.driver.quit()
def test_select_all(self):
"""下拉框全选后再反选"""
se = self.driver.find_element_by_id('provise')
select = Select(se)
for i in range(3): #全选
select.select_by_index(i)
sleep(1)
sleep(3)
select.deselect_all() #反选
sleep(3)
def test_select_option(self):
"""打印出来下拉框数据"""
se = self.driver.find_element_by_id('provise')
select = Select(se)
for option in select.options:
print(option.text)
if __name__ == '__main__':
case=testcase()
#case.test_select()
#case.test_select_all()
case.test_select_option()