千家信息网

selenium学习:不同方式定位元素

发表于:2025-02-05 作者:千家信息网编辑
千家信息网最后更新 2025年02月05日,文件名:checkbox.htmlCheckbox Checkbox
千家信息网最后更新 2025年02月05日selenium学习:不同方式定位元素

文件名:checkbox.html

Checkbox                

Checkbox

文件名:test.py

from selenium import webdriverimport os,timedriver = 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.clickpop(-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元素,属于同类别元素


0