{{announcement.body}}
{{announcement.title}}

Complete Guide To Selenium Locators In Protractor (Examples)

DZone 's Guide to

Complete Guide To Selenium Locators In Protractor (Examples)

Selenium locators serve this exact purpose — to perform Selenium test automation through our scripts.

· Performance Zone ·
Free Resource

While testing the functionality for your website, especially web elements such as radio button, text boxes, drop-down, etc., you need to make sure that you can access these elements. Selenium locators serve this exact purpose, by using this command we can identify these web elements, DOM (Document Object Model), to perform Selenium test automation through our scripts.

These Selenium locators are vital for scripting as if they’re wrong, your automation scripts won’t work. Thus your Selenium test automation efforts rely on these Selenium locators in any testing framework. Protractor, an Angular JS framework, has many Selenium locators that can be identified by using a specific By method during runtime.

In this protractor testing tutorial, we will discuss the Selenium locators in Protractor in-depth and how we can use locators to interact with the application and fetch the current running state. So, let’s get started.

What Is Protractor?

Protractor is a Selenium test automation framework developed by the team at Google and mainly used for application with frontend technologies like AngularJS. This end to end test framework mimics the access to the web application just like a real user would perform any activity on the browser and automatically execute our test cases. It offers a behavior driver development interface and hence it is convenient to execute our test cases. 

Additionally, the continuous synchronization feature executes the next task on the web page soon after the completion of the previous pending activities is completed. 

Finally, it supports Angular specific strategies, so that we can effortlessly test elements provided by Angular and we will be looking at it in detail further in this post.

What Is The Importance Of Selenium Locators In Protractor?

Let’s start our protractor testing tutorial by discussing various features that should be kept in mind when choosing a locator concerning its performance. The Selenium locators in Protractor have proven to be good and reliable in most scenarios. Some of the features that it provides are:

Good Readability

  • The Selenium locators in the protractor are easily readable and accessible. The locators offer enough flexibility to the test code by making it accessible to the user.

Less Maintenance

  • The Selenium locators in Protractor are developed in an optimized manner and hence, they require less maintenance overhead.

  • The structure of the locator is designed in a great fashion so that there is no need to update the locator even when there is a change in the location of the element. It requires modification only if there is any change in the functionality of the web application.

Improved Speed

  • This is one of the most important properties of the Selenium locators as this feature determines the performance of the web application. The Selenium locators in the protractor have a unique id which makes them relatively faster than other Selenium locators. Sometimes, the speed of locating an element is also dependent on the internal processing speed of the browsers.

The Objective of Selenium Locators in Protractor

Moving on with our protractor testing tutorial, we’ll discuss the importance of Selenium locators. The important point to remember to write good end to end tests in Protractor is discovering the proper Document Object Model (DOM) elements for the web pages. 

It tends to globally export locator factories through instantiated objects. Since the protractor is built upon Selenium interfaces, the Selenium locators in the protractor are quite comparable and similar to the ones associated with Selenium WebDriver. Therefore, it is interesting to know that the framework supports Selenium locators in Protractor as well along with its own.

Working of Selenium Locators in Protractor

Next, in this protractor testing tutorial, we’ll discuss how Selenium locators work in Protractor. The way the locator functions in Protractor is by exporting a global function i.e. ‘element’, which inputs the locator and provides us with the ElementFinder in return.

 The ElementFinder, on the other hand, offers a fundamental way to communicate with an element and get details about the same with various action methods such as getText(), click() and sendKeys(). These methods are quite popular and are used frequently when executing Selenium test automation.

The main purpose of the ‘element’ function is to locate a single element. To locate multiple elements, the ‘element.all’ the function is used. 

There are several other means by which we can find the elements in Protractor and by using elements locating strategies in Angular JavaScript framework such as by.model(), by.repeater(), by.binding(), etc.

List of Selenium Locators in Protractor

Now in this section of protractor testing tutorial, let's get familiar with global variables that are majorly used in locating the DOM elements with examples for better understanding of these Selenium locators in protractor. These are a group of element locator strategies that are associated with the “by” keyword such as by.className, by.css, by.model, etc. Some of the most commonly used are:

By.className 

The className locator is one of the most widely used Selenium locators in Protractor. ts objective is to check for the elements in the page with a class attribute and then further classify the elements specific to their class name. 

For Example:

Sample XML Document:

XML
 




xxxxxxxxxx
1


 
1
/* The list contains a class for positive or negative */
2
 
3
<ul class="digits">
4
  <li class="positive">5</li>
5
  <li class="negative">-6</li>
6
</ul>
7
 
          



Locator Used:

Java
 




xxxxxxxxxx
1


1
/* The locator that returns the expected element for the specified class */
2
 
3
var even = browser.findElement(by.className(positive));
4
expect(even.getText()).toBe('5');
5
// making use of our locator in our test script //
6
expect(browser.findElement(by.className('even'))).toBe('-6');
7
 
          



By.id  

The Id locator is used to discover an element in the web page based on the id attribute defined in the XML document structure. 

For Example:

Sample XML Document:

XML
 




xxxxxxxxxx
1


 
1
/* The list contains class for positive or negative */
2
 
3
<ul class="digits">
4
  <li class="negative">-6</li>
5
  <li class="positive" id="positiveNumber">5</li>
6
</ul>
7
 
          



Locator Used:

Java
 




xxxxxxxxxx
1


1
/* The locator that returns the expected element for the specified id */
2
 
3
// making use of our locator in our test script //
4
var positive = browser.findElement(by.id('positiveNumber'));
5
expect(positive.getText()).toBe('5');
6
 
          



By.css  

The CSS locator assists in identifying the elements and classify them based on the CSS selector i.e. the identifier value used to distinguish the element existing on the web page. These Selenium locators are also one of the most preferred substitutes in Protractor when we do not have a choice to select based on class name or id.

For Example:

Sample XML Document:

XML
 




xxxxxxxxxx
1


 
1
/* The list contains class for two color i.e blue or red */
2
 
3
<ul class="color">
4
  <li class="first">blue</li>
5
  <li class="second" id="secondColor">red</li>
6
</ul>
7
 
          



Locator Used:

Java
 




xxxxxxxxxx
1


1
/* The locator that returns the expected element for the specified CSS */
2
 
3
var first = browser.findElement(by.css('.first'));
4
expect(first.getText()).toBe('blue');
5
// making use of our locator in our test script //
6
expect(browser.findElement(by.css('#secondColor'))).toBe('red');
7
 
          



By.linkText

The objective of the linkText locator is to identify the matching string text corresponding to the anchor element i.e. <a> tag in the DOM. It works only on the hyperlink and by default, the first link text is selected if there are multiple elements present for the link text on the web page.

For Example:

Sample XML Document:

XML
 




xxxxxxxxxx
1


1
/* The anchor tag which contains the website name and its URL */
2
 
3
<a href="http://www.lambdatest.com">LambdaTest</a>
4
 
5
<a href="http://www.lambdatest.com">LambdaTest</a>
6
 
          



Locator Used:

Java
 




xxxxxxxxxx
1


1
/* The locator that returns the expected element for the link i.e. Lambda Test*/
2
 
3
// making use of our locator in our test script //
4
var myLink = element(by.linkText(‘LambdaTest'));
5
 
6
expect(myLink.getTagName()).toBe('a');
7
 
          



By.name 

The name locator is used to discover the element having the specific value in the name attribute.

For Example:

Sample XML Document:

XML
 




xxxxxxxxxx
1
10


 
1
/* The list contains a class for two names i.e John and Mark */
2
 
3
<ul>
4
 
5
  <li name="developer">John</li>
6
 
7
  <li name="tester">Mark</li>
8
 
9
</ul>
10
 
          



Locator Used:

Java
 




xxxxxxxxxx
1
12


1
/* The locator that returns the expected element for the specified name */
2
 
3
// making use of our locator in our test script //
4
var developer = browser.findElement(by.name('developer'));
5
 
6
// making use of our locator in our test script //
7
var tester = browser.findElement(by.name('tester'));
8
 
9
expect(developer.getText()).toBe('John');
10
 
11
expect(tester.getText()).toBe('Mark');
12
 
          



By.partialLinkText

The partialLinkText locator is used in scenarios where there is a need to find the elements which contain the string or the portion of the string in the link text element. 

For Example:

Sample XML Document:

XML
 




xxxxxxxxxx
1


 
1
/* The list contains anchor tag which has the required text */
2
 
3
<ul>
4
  <li><a href="http://www.lambdatest.com"> Selenium test automation Cloud</a></li>
5
  <li>Online Selenium Grid for Automated Testing</li>
6
</ul>
7
 
          



Locator Used:

Java
 




xxxxxxxxxx
1


1
// /* The locator that returns the expected element i.e. gives us the 'a' element value ‘Selenium test automation Cloud’ and navigates to the same link */
2
 
3
// making use of our locator in our test script //
4
var myLink = browser.findElement(by.partialLinkText('Cloud'));
5
 
6
myLink.click();
7
 
          



By.tagName 

The tagName locator is used to locate elements having a specific tag name. It looks for elements in the web page having any tag name like <a>,  <div>, <p> etc. It functions similar to that of the getElementsByTagName function used in the XML document structure.

For Example:

Sample XML Document:

XML
 




xxxxxxxxxx
1


 
1
/* The list contains anchor tag which has the required text */
2
 
3
<a href="http://www.lambdatest.com">LambdaTest</a>
4
 
          



Locator Used:

Java
 




xxxxxxxxxx
1


 
1
// /* The locator that returns the expected element i.e. gives us the 'a' tag  value and that matches with the text given */ //
2
 
3
// making use of our locator in our test script //
4
expect(element(by.tagName('a')).getText()).toEqual('LambdaTest');
5
 
          



By.xpath

The Xpath locator is used to find the matching element for the XML Xpath Selector provided. An important thing to note when dealing with XPath Selenium locators is that to search and element the entire XML document model we must we begin our XPath locator with “//” 

Example:

XPath = //*[@value='Inbox'] - matches with Inbox

xpath=//button[@name="Gma"] - matches with Gmail

For Example:

Sample XML Document:

XML
 




xxxxxxxxxx
1


 
1
/* The list contains anchor tag which has the required text */
2
 
3
<ul>
4
  <li><a href="http://www.lambdatest.com">Selenium test automation Cloud </a> </li>
5
  <li> Online Selenium Grid for Automated Testing </li>
6
</ul>
7
 
          



Locator Used:

Java
 




xxxxxxxxxx
1


1
// /* The locator that returns the expected element i.e. gives us the 'a' tag  value with the help of XPath and that matches with the text given */
2
 
3
// making use of our locator in our test script //
4
var xpathEle = browser.findElement(by.xpath('//ul/li/a'));
5
 
6
expect(xpathEle.getText()).toBe(‘Selenium test automation Cloud’);
7
 
          



Angular Specific Selenium Locators

Now, in this protractor testing tutorial, let us have a look at some of the Selenium locators that are used in Angular but are also available for the Protractor framework.

By.model

The model locator identifies the element having the exact text associated with the ng-model attribute.

For Example:

Sample XML Document:

XML
 




xxxxxxxxxx
1


 
1
// /* The XML input type contains the text with the model attribute */ //
2
 
3
<input type="text" ng-model="developer.name">
4
 
          



Locator Used:

Java
 




xxxxxxxxxx
1


 
1
// /* The locator finds the element with the model attribute and returns the value */ //
2
 
3
// making use of our locator in our test script //
4
element(by.model('developer.name')).click();
5
 
          



By.buttonText

The buttonText locator finds a match with an element having the same text of the button tag or inside the sub-element of the tag.

For Example:

Sample XML Document:

XML
 




xxxxxxxxxx
1


 
1
// /* The XML contains the button with the required value */ //
2
 
3
<button> Selenium test automation Cloud </button>
4
 
          



Locator Used:

Java
 




xxxxxxxxxx
1


 
1
// /* The locator finds the element with the button tag and returns the value */ //
2
 
3
// making use of our locator in our test script //
4
element(by.buttonText('Selenium test automation Cloud'));
5
 
          



By.partialButtonText

The partialButtonTextlocator finds a match with an element that contains the part of the text i.e. partial match in the button tag or inside the sub-element of the tag.

For Example:

Sample XML Document: 

XML
 




xxxxxxxxxx
1


 
1
// /* The XML contains the button with the required value */ //
2
 
3
<button> Selenium test automation Cloud </button>
4
 
5
 
          



Locator Used:

Java
 




xxxxxxxxxx
1


 
1
// /* The locator finds the element with the button tag and returns the value */ //
2
 
3
// making use of our locator in our test script //
4
element(by.partialButtonText('Cloud'));
5
 
          



By.exactBinding

The exactBinding locator is used to locate the ng-bind attribute with the exact string/text value provided. It will not check for any partial matches in the text.

For Example:

Sample XML Document: 

XML
 




xxxxxxxxxx
1


 
1
// /* The XML input type contains the text with the bind attribute */ //
2
 
3
<p ng-bind="developer.name"></p>
4
 
          



 Locator Used:

Java
 




xxxxxxxxxx
1


1
// /* The locator finds the element with the bind attribute and returns the value */ //
2
 
3
// making use of our locator in our test script //
4
expect(element(by.exactBinding('developer.name')).isPresent()).toBe(true);
5
 
          



By.binding

This binding locator is used to locate the ng-bind attribute with the given text value. It also helps in locating the text that is a partial match, i.e. if there is an attribute that has some matching with a given locator then this element will be found by our locator, so the relevant matching elements are returned.

For Example:  

Sample XML Document:

XML
 




xxxxxxxxxx
1


 
1
// /* The XML input type contains the text with the bind attribute */ //
2
 
3
<p ng-bind="developer.name">John</p>
4
 
          


 

Locator Used:

Java
 




xxxxxxxxxx
1


 
1
// /* The locator finds the element with the bind attribute and returns the value */ //
2
 
3
// making use of our locator in our test script //
4
var eleName = element(by.binding(developer));
5
expect(eleName.getText()).toBe('John');
6
 
          


By.exactRepeater 

The exactRepeater locator identifies the element having the exact text associated with attribute ng-repeat. It will not check for any partial matches in the text.

For Example:

Sample XML Document:

XML
 




xxxxxxxxxx
1


 
1
// /* The XML input type contains the text with the bind attribute */ //
2
 
3
<li ng-repeat="dev in developer_names"></li>
4
 
5
<li ng-repeat="test in tester_names"></li>
6
 
          



Locator Used:

Java
 




xxxxxxxxxx
1


1
// /* The locator finds the element with the bind attribute and returns the exact value */ //
2
 
3
// making use of our locator in our test script //
4
 
5
expect(element(by.exactRepeater('dev in developer_names')).isPresent()).toBe(true);
6
 
          



By.repeater

The repeater locator is used to find the element that has the attribute ng-repeat. It also helps in locating the text that is a partial match, i.e. if there is an attribute that has some matching with a given locator then this element will be found by our locator, so the relevant matching elements are returned.

For Example:

Sample XML Document:

XML
 




xxxxxxxxxx
1


 
1
// /* The XML input type contains the text with the repeater attribute */ //
2
 
3
<tr ng-repeat="developer_info">
4
    <td>{{dev.id}}</td>
5
    <td>{{dev..name}}</td>
6
    <td>{{dev.salary}}</td>
7
</tr>
8
 
          



Locator Used:

Java
 




xxxxxxxxxx
1
10


1
// /* The locator finds the element with the repeater attribute and returns the value */ //
2
 
3
// making use of our locator in our test script //
4
 
5
var devID = element(by.repeater('developer_info').row(0));
6
expect(devID.getText()).toBe('2');
7
 
8
var devName = element(by.repeater('developer_info').row(1));
9
expect(devName.getText()).toBe('Mark');
10
 
          



By.cssContainingText 

The cssContainingText locator finds the element by CSS having the specific text string, i.e. it combines the function of the CSS locator and the text element locator to identify the element.

For Example:  

Sample XML Document:

XML
 




xxxxxxxxxx
1


1
// /* The XML input type contains the text with the css text */ //
2
 
3
<ul>
4
  <li class="color">Blue</li>
5
  <li class="color">Red</li>
6
</ul>
7
 
          



Locator Used:

Java
 




xxxxxxxxxx
1


1
// /* The locator finds the element and returns the value for the Blue color but not the Red color */ //
2
 
3
// making use of our locator in our test script //
4
 
5
var blue = element(by.cssContainingText('.color', 'Blue'));
6
 
          


By.options  

The options locator identifies the element associated with attribute ng-option.

For Example:  

Sample XML Document:

XML
 




xxxxxxxxxx
1


 
1
// /* The XML input type contains the text with the option attribute */ //
2
 
3
<select ng-options="Colors options in the custom collection">
4
  <option value="0">Blue Color</option>
5
  <option value="1">Red Color</option>
6
  <option value="2">Green Color</option>
7
</select>
8
 
          



Locator Used:

Java
 




xxxxxxxxxx
1


1
// /* The locator finds the element with the options attribute and returns the value */ //
2
 
3
// making use of our locator in our test script //
4
 
5
var colorOptions = element.all(by.options('Colors options in the custom collection'));
6
expect(colorOptions.count()).toEqual(Green);
7
 
          



By.deepCss

The deepCss locator in protractor is used to discover the shadow DOM elements, which by default is not easily discoverable by using standard element Selenium locators.  

For Example:  

Sample XML Document:

XML
 




xxxxxxxxxx
1
12


 
1
// /* The XML input type contains the text and returns the fetched value */ //
2
 
3
<div>
4
  <span id="outerspan">   //outerspan
5
  <"shadow tree">           //shadow tree
6
    <span id="span1"></span>
7
    <"shadow tree">
8
      <span id="span2"></span>
9
    </>
10
  </>
11
</div>
12
 
          



Locator Used:

Java
 




xxxxxxxxxx
1
11


 
1
// /* The locator finds the element with the options attribute and returns the value */ //
2
 
3
// making use of our locator in our test script //
4
 
5
var mySpan = element.all(by.deepCss('span'));  //myspan
6
expect(mySpan.count()).toEqual(7);
7
// making use of our locator in our test script //
8
 
9
var checkSpans = element.all(by.css('span');  //verify span
10
expect(checkSpans.count()).toEqual(5);
11
 
          



In this next section of the protractor testing tutorial, we’ll discuss how you can integrate protractor with other powerful tools. Before that, if you want to set up a protractor to run your Selenium automation scripts you can check out our support documentation.

By.addLocator

The addLocator in protractor is used to create custom locators and load them later in the config

For Example:  

Sample XML Document:

XML


Locator Used:

Java
 




xxxxxxxxxx
1
12


1
// /* The locator finds the element with the options attribute and returns the value */ //
2
 
3
// making use of our locator in our test script //
4
 
5
by.addLocator('Selenium Grid',function(buttonText, opt_parentElement, opt_rootSelector) {
6
var using = opt_parentElement || document,
7
buttons = using.querySelectorAll(‘Automate testing’);
8
return Array.prototype.filter.call(buttons, function(button) {
9
return button.textContent === buttonText;
10
});
11
});
12
 
          



Conclusion

As we have seen in this protractor testing tutorial, that since protractor is built upon Selenium and mostly used for Angular websites, it inherits properties from them. This is the reason we use Selenium locators in protractors, and it adds more charm to the framework and makes it more robust when used to the fullest.

On the other hand, protractor is not just about Selenium locators there are many other aspects and features of the protector testing available for use in the market which adds more, that we will cover eventually in our protractor testing tutorials. 

Topics:
locators in selenium ,performance ,protractor ,selenium ,selenium automation ,tutorial

Published at DZone with permission of Ramit Dhamija . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}