Selenium locators help us to find the web element on which we wish to perform any operation. These web elements could be anything from textbox, button to even hardcoded string that we are found in almost all the sites on the internet.
Since all the web pages are constructed based on DOM so web element tend to structured and that we can be able to find or locate these structured web element on a list of ways.
Before that we will be practicing locator on the below site http://automationpractice.com/index.php, Use developer option in the browser to inspect the Web page to find the web element you are looking to use it in your selenium script.
1. Class name
Syntax :
driver.find_element_by_class_name()
2. Element ID
Syntax :
driver.find_element_by_id()
Using the inspect element look for the ID inside HTML. After you find the ID we can pass some value to make sure we have selected the correct web element.
Then our locator will completely look like below line,
driver.find_element_by_id("search_query_top").send_keys("Faded Short Sleeve T-shirts", Keys.ENTER)
3. Xpath
Syntax :
driver.find_element_by_xpath()
There are 2 types of Xpath
Absolute Xpath
Relative Xpath
Absolute Xpath
It contains the complete path from the Root Element to the desire element. Lets try to get Absolute Xpath for the Contact Us.
As you can see from the given pic above in order to reach Contact us we have to navigate from <html> to <div>/<a> and our Absolute Xpath would be like
/html/body/div/div[1]/header/div[2]/div/div/nav/div[2]/a
4. CSS Selector
Syntax :
driver.find_element_by_css_selector()
I
5. Tag name
Syntax :
driver.find_element_by_tag_name()
driver
6. Partial Link
Syntax :
driver.find_element_by_partial_link_text()
Syntax
7. Link Text
Syntax :
driver.find_element_by_link_text()
Syntax
I have attached Cloud Test below for reference,