Selenium Learning: positioning elements in different ways
File name: checkbox.html
Checkbox Checkbox checkbox1 Checkbox2 Checkbox3
File name: test.py
From selenium import webdriverimport os Timedriver = webdriver.Chrome () file_path=' file:///'+os.path.abspath('checkbox.html')driver.get(file_path)# snippet 1: inputs = driver.find_elements_by_tag_name ('input') for i in inputs: if i.get_attribute (' type') = = 'checkbox': i.click () time.sleep (1) # snippet 2: # find it through XPath Element to type=checkbox checkboxes=driver.find_elements_by_xpath ("/ / input [@ type='checkbox']") # find type=chekcbox element checkboxes=driver.find_elements_by_css_selector ("input [type=checkbox]") for checkbox in checkboxes: checkbox.click () time.sleep (1) # Code snippet 3: 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 () gets the last pop (0) in a set of elements by default, gets the first pop (1) in a set of elements, and gets the second driver.quit () in a set of elements.
In the above test.py code
Code snippet 1: get input through find_elements_by_tag_name ('input'). The acquired input element contains type and id attributes, so it is not unique. Use the get_attribute method to specify the corresponding attribute to find the unique element, checkbox, thus determining the location of the element.
Code chip 2: get a series of checkbox elements through find_elements_by_xpath, belonging to the same category elements
Get a series of checkbox elements that belong to the same category through find_elements_by_css_selector