您的位置:首页 > 编程语言 > Python开发

selenium_webdriver(python)单/复选框的遍历选择

2015-04-30 16:36 363 查看
wml.html:

<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Checkbox</title>
</head>
<body>
<h3>checkbox</h3>
<form>
<!-- <label for="c1">checkbox1</label> -->
<input type="checkbox" id="c1" />checkbox1<br>
<!-- <label for="c2">checkbox2</label> -->
<input type="checkbox" id="c2" />checkbox2<br>
<!-- <label for="c3">checkbox3</label> -->
<input type="checkbox" id="c3" />checkbox3<br>
</form>

<form>
<label  value="radio">radio</label>
<input type="radio"   name="sex" value="male" id="as"/><br>
<label  value="radio1">radio</label>
<input type="radio"   name="sex" value="female" id="sd"/>
</form>

<!-- <form>
<input type="radio" name="sex" value="male" /> Male
<br />
<input type="radio" name="sex" value="female" /> Female
</form> -->

</body>
</html>


#coding: utf-8
#以下代码用来遍历所有复选框
from selenium import webdriver
import time
import os
driver = webdriver.Chrome()
#获取要测试文件绝对路径
file_path = os.path.abspath('wml.html')
print file_path
#用浏览器打开文件
driver.get(file_path)
# 选择页面上所有的input,然后从中过滤出所有的checkbox 并勾选之
inputs = driver.find_elements_by_tag_name('input')
for input in inputs:
if input.get_attribute('type') == 'checkbox':
input.click()
time.sleep(2)
'''
checkboxs = driver.find_elements_by_css_selector('input[type=checkbox]')
for checkbox in checkboxs:
checkbox.click()
time.sleep(2)
'''
# 把页面上最后1个checkbox 的勾给去掉
#.pop() 方法用于删除并返回数组的最后一个元素,在此处是返回到复选框的“最后一个”按钮
driver.find_elements_by_css_selector('input[type=checkbox]').pop().click()
time.sleep(2)
driver.quit()



#coding: utf-8
##以下代码用来遍历所有单选框
from selenium import webdriver
import time
import os
dr = webdriver.Chrome()
file_path = os.path.abspath('wml.html')
dr.get(file_path)
# 选择所有的radio并全部勾上
radios = dr.find_elements_by_css_selector('input[type=radio]')
for radio in radios:
radio.click()
time.sleep(2)
time.sleep(2)
dr.quit()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: