定位一组元素的方法与定位单个元素的方法类似,唯一的区别就是在单词element后面多加了个s表示复数。定位一组元素多用于以下场景:
*批量操作元素
*先获取一组元素,再从这组元素对象中过滤出需要操作的元素。
1.
from selenium import webdriver
import os,time
driver =webdriver.Chrome()
file_path='file:///'+os.path.abspath('./webdriver_api/web_page/checkbox.html')
driver.get(file_path)
#选择页面上所有tag name 为input 的元素
inputs =driver.find_elements_by_tag_name('input')
#然后从中过滤出type 为checkbox的元素,单击勾选
for i in inputs:
if i.get_attribute('type')=='checkbox':
i.click()
time.sleep(1)
driver.quit()
2.使用XPath或CSS来直接判断属性值,从而进行单击操作。
from selenium import webdriver
import os,time
driver =webdriver.Chrome()
file_path='file:///'+os.path.abspath('./webdriver_api/web_page/checkbox.html')
driver.get(file_path)
#通过XPath找到type=checkbox 的元素
checkboxes =driver.find_elements_by_xpath("//input[@type='checkbox']")
#通过CSS找到type=checkbox的元素
checkboxes =driver.find_elements_by_css_selector('input[type=checkbox]')
for checkbox in checkboxes:
checkbox.click()
time.sleep(1)
#打印当前页面上type为checkbox的个数
print(len(checkboxes))
#把页面上最后一个checkbox的钩给去掉
driver.find_elements_by_css_selector('input[type=checkbox]').pop().click()
time.sleep(2)
driver.quit()