Selinum定位一组元素

 

 1.勾选3个复选框

  方法一:

 1 # -*- coding: utf-8 -*-
 2 from selenium import webdriver
 3 import time
 4 import os
 5 dr = webdriver.Firefox()
 6 file_path = 'file:///' + os.path.abspath('checkbox.html')
 7 dr.get(file_path)
 8 # 选择页面上所有的input,然后从中过滤出所有的checkbox 并勾选之
 9 inputs = dr.find_elements_by_tag_name('input')
10 for input in inputs:
11   if input.get_attribute('type') == 'checkbox':
12     input.click()
13 time.sleep(2)
14 dr.quit()

方法二:

 1 # -*- coding: utf-8 -*-
 2 from selenium import webdriver
 3 import time
 4 import os
 5 dr = webdriver.Firefox()
 6 file_path = 'file:///' + os.path.abspath('checkbox.html')
 7 dr.get(file_path)
 8 # 选择所有的checkbox 并全部勾上
 9 checkboxes = dr.find_elements_by_css_selector('input[type=checkbox]')
10 for checkbox in checkboxes:
11   checkbox.click()
12 time.sleep(2)
13 # 打印当前页面上有多少个checkbox
14 print len(dr.find_elements_by_css_selector('input[type=checkbox]'))
15 time.sleep(2)
16 dr.quit()

2.去掉最后一个勾选

 1 # -*- coding: utf-8 -*-
 2 from selenium import webdriver
 3 import time
 4 import os
 5 dr = webdriver.Firefox()
 6 file_path = 'file:///' + os.path.abspath('checkbox.html')
 7 dr.get(file_path)
 8 # 选择所有的checkbox 并全部勾上
 9 checkboxes = dr.find_elements_by_css_selector('input[type=checkbox]')
10 for checkbox in checkboxes:
11   checkbox.click()
12 time.sleep(2)  
13
14 # 把页面上最后1个checkbox 的勾给去掉 15 dr.find_elements_by_css_selector('input[type=checkbox]').pop().click() 16
17 time.sleep(2) 18 dr.quit()

 

 

 

 

命运最好的轨迹是大成功伴随着小失败交错前行,怕的是一直都很顺,太顺了就容易产生非理性的勇敢和勇气,也容易滋生自大和盲目,特别是取得一定的成功之后特别容易出现的问题,而这正是一个人覆灭的充分条件。

posted @ 2022-12-28 18:07  心如__止水  阅读(41)  评论(0编辑  收藏  举报