checkbox.html源码:
<html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <title>Checkbox</title> <script type="text/javascript" async="" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" /> <script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script> </head> <body> <h3>checkbox</h3> <div class="well"> <form class="form-horizontal"> <div class="control-group"> <label class="control-label" for="c1">checkbox1</label> <div class="controls"> <input type="checkbox" id="c1" /> </div> </div> <div class="control-group"> <label class="control-label" for="c2">checkbox2</label> <div class="controls"> <input type="checkbox" id="c2" /> </div> </div> <div class="control-group"> <label class="control-label" for="c3">checkbox3</label> <div class="controls"> <input type="checkbox" id="c3" /> </div> </div> <div class="control-group"> <label class="control-label" for="r">radio</label> <div class="controls"> <input type="radio" id="r" /> </div> </div> </form> </div> </body> </html>
Python代码:
#coding=utf-8 from selenium import webdriver import time import os dr = webdriver.Firefox() file_path = 'file:///' + os.path.abspath('checkbox.html') dr.get(file_path) # 选择所有的checkbox并全部勾上 checkboxes = dr.find_element_by_css_selector('input[type=checkbox]') for check in checkboxes: check.click() time.sleep(1) # 打印当前页面上有多少个checkbox dr.quit()
报错内容:TypeError: 'WebElement' object is not iterable
解决办法:
checkboxes = dr.find_element_by_css_selector('input[type=checkbox]')
改为:
checkboxes = dr.find_elements_by_css_selector('input[type=checkbox]')