Locating Elements
Location Methods:
find_element_by_idfind_element_by_namefind_element_by_xpathfind_element_by_link_textfind_element_by_partial_link_textfind_element_by_tag_namefind_element_by_class_namefind_element_by_css_selectorfind_elements_by_namefind_elements_by_xpathfind_elements_by_link_textfind_elements_by_partial_link_textfind_elements_by_tag_namefind_elements_by_class_namefind_elements_by_css_selector
Example usage:
from selenium.webdriver.common.by import Bydriver.find_element(By.XPATH, '//button[text()="Some text"]')driver.find_elements(By.XPATH, '//button')
By class attributes:
ID = "id"XPATH = "xpath"LINK_TEXT = "link text"PARTIAL_LINK_TEXT = "partial link text"NAME = "name"TAG_NAME = "tag name"CLASS_NAME = "class name"CSS_SELECTOR = "css selector"
1.Locating by Id
Page source:
login_form = driver.find_element_by_id('loginForm')
2.Locating by Name
Page source:
username = driver.find_element_by_name('username')password = driver.find_element_by_name('password')continue = driver.find_element_by_name('continue') //"Login" button,it occures before the "Clear" button
3.Locating by XPath
Page source:
//locating formlogin_form = driver.find_element_by_xpath("/html/body/form[1]")login_form = driver.find_element_by_xpath("//form[1]")login_form = driver.find_element_by_xpath("//form[@id='loginForm']")//locating usernameusername = driver.find_element_by_xpath("//form[input/@name='username']")username = driver.find_element_by_xpath("//form[@id='loginForm']/input[1]")username = driver.find_element_by_xpath("//input[@name='username']")//locating "Clear"clear_button = driver.find_element_by_xpath("//input[@name='continue'][@type='button']")clear_button = driver.find_element_by_xpath("//form[@id='loginForm']/input[4]")
4.Locating Hyperlinks by Link Text
Page source:
Are you sure you want to do this?
Continue Cancelcontinue_link = driver.find_element_by_link_text('Continue')continue_link = driver.find_element_by_partial_link_text('Conti')
5.Locating Elements by Tag Name
Page source:
Welcome
Site content goes here.
heading1 = driver.find_element_by_tag_name('h1')
6.Locating Elements by Class Name
Page source:
Site content goes here.
content = driver.find_element_by_class_name('content') //Locating "p" element
7.Locating Elements by CSS Selectors
Page source:
Site content goes here.
content = driver.find_element_by_css_selector('p.content') Locating "p" element
节选自Selenium官网Doc:
https://selenium-python.readthedocs.io/locating-elements.html