文件名:test.py
from selenium import webdriver
import os,time
driver = webdriver.Chrome()
file_path='file:///'+os.path.abspath('checkbox.html')
driver.get(file_path)
#代码片段一:
inputs = driver.find_elements_by_tag_name('input')
for i in inputs:
if i.get_attribute('type')=='checkbox':
i.click()
time.sleep(1)
#代码片段二:
#通过XPath找到type=checkbox的元素
checkboxes=driver.find_elements_by_xpath("//input[@type='checkbox']")
#通过CSS找到type=chekcbox的元素
checkboxes=driver.find_elements_by_css_selector("input[type=checkbox]")
for checkbox in checkboxes:
checkbox.click()
time.sleep(1)
#代码片段三:
inputs = driver.find_elements_by_tag_name('input')
for i in inputs:
if i.get_attribute('id')=='c1':
i.click()
time.sleep(3)
driver.find_elements_by_css_selector("input[type=checkbox]").pop.click
pop(-1)、pop()默认获取一组元素中的最后一个
pop(0)获取一组元素中的第一个
pop(1)获取一组元素中的第二个
driver.quit()
上述test.py代码中,
代码片段一:通过find_elements_by_tag_name('input')获取input,获取到的input元素包含type和id属性,因此不唯一,通过get_attribute方法指定对应的属性找到唯一元素,checkbox,从而确定了元素的定位
代码片二:通过find_elements_by_xpath获取到一系列的checkbox元素,属于同类别元素
通过find_elements_by_css_selector获取到一系列的checkbox元素,属于同类别元素
本文名称:selenium学习:不同方式定位元素
文章URL:
http://www.zsjierui.cn/article/gpsoie.html