Locating WebElements is the job to find and match the elements of your page that it needs to interact with. It contains “Find Element” and “Find Elements” method. The first returns a WebElement object otherwise it throws an exception. The latter returns a list of WebElements, it can return an empty list if no DOM elements match the query.
Browser Tools For Element Inspection:
- Firefox – ‘Firebug’ add-on (right click → ‘Inspect Element’ / F12)
- Chrome – Built-in page analyzing feature (right click → ‘Inspect Element’ / F12)
- IE – Developers tool (‘Tools’ → ‘Developers Tools’ / F12)
Below are common locators strategies used in Selenium:
- By ID
- By Class Name
- By Tag Name
- By Name
- By Link Text/Partial Link Text
- By Css Selector
- By Xpath
By ID
WebElement element = driver.findElement(By.id("Selenium"));
By Class Name
WebElement element = driver.findElement(By.className("WebDriver"));
By Tag Name
WebElement element =driver.findElement(By.tagName("textarea"));
By Link Text/ Partial Link Text
WebElement element = driver.findElement(By.linkText("Test Execution"));//By linktext
WebElement element = driver.findElement(By.partialLinkText("Execution"));//By Partial linktext
By Css Selector
CSS – Cascading Style Sheets – language used for describing the presentation semantics of a document written in a markup language such as HTML or XML.
In CSS, selectors are patterns used to select the element(s) you want to style.
In selenium, we can use CSS selector to indicate the element that need to be interacted.
Below are some basic syntaxs of CSS Selector:
Example:
WebElement element;
element = driver.findElement(By.cssSelector("#comment-issue")); //using id
element = driver.findElement(By.cssSelector("ul#comment-issue")); "));//using id and tag
element = driver.findElement(By.cssSelector("ul#comment-issue[title~='issue']")); //using id,tag and partial of attribute
WebElement element;
element = driver.findElement(By.cssSelector(".issue-link") //using class
element = driver.findElement(By.cssSelector(".issue-link[title='WebDriver']") //using class and attribute
element = driver.findElement(By.cssSelector("a.issue-link[title='WebDriver']") //using tag, class and attribute
element = driver.findElement(By.cssSelector(".stsumary a.issue-link") //using many class levels – 'issue-link' is a child of 'stsumary' class
Read more about Css Selector here
By Xpath
- Xpath is a query language for selecting nodes from an XML document.
- Xpath is based on a tree representation of the XML document and provides the ability to navigate around the tree. The most useful path expressions are listed below:
In the table below we have listed some path expressions and the result of the expressions:
Read more about Xpath here



















