Locating UI Elements (WebElements)

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:

  1. By ID
  2. By Class Name
  3. By Tag Name
  4. By Name
  5. By Link Text/Partial Link Text
  6. By Css Selector
  7. By Xpath

By ID

By ID

WebElement element = driver.findElement(By.id("Selenium"));

By Class Name

By Class

WebElement element = driver.findElement(By.className("WebDriver"));

By Tag Name

By tagName

WebElement element =driver.findElement(By.tagName("textarea"));

By Link Text/ Partial Link Text

linkText

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:

cssSelector

Example:

ID and tag

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

class_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:

Xpath expression

In the table below we have listed some path expressions and the result of the expressions:

Xpath example

Read more about Xpath here

Leave a comment