https://www.qatechies.com

How to find web elements using CSS Selectors?

How to find web elements using CSS Selectors

How to find web elements using CSS Selectors?


Welcome to this post!-“How to find web elements using CSS Selectors?”

If you are looking for latest Selenium Webdriver concepts related to interview questions, then you are at right place. This post – “ How to find web elements using CSS Selectors?” consists of discussion on CSS Selectors and some examples.

Plus this post will give a broader perspective on the usage and implementation of CSS Selectors usage while using java in Selenium.

Usually these are assumed to be known in depth to check the logical solvency efficiency of the candidate and of course, suitability for the project and company. Go ahead and enjoy reading…

This discussion will help you prepare well if you are going for the interview or you need the function to be used in your project.

In the interview usually, you might be questioned in different ways like:

  1. How to get web elements using absolute path when considering css?
  2. How can you locate input web elements on web application using selenium where id’s are generated dynamically?
  3. Which combinators and pseudo classes are part of CSS Selectors?
  4. Can you track user actions using CSS in selenium? If yes then how.

And so on.

 

Understanding CSS Selectors Usage in Selenium

The following article consists of following sub topics:

  1. What is CSS?
  2. How Selenium Webdriver identifies elements using this CSS selector.
  3. How to get the web elements with absolute path.
  4. How to get the web elements with relative path.
  5. How to identify web elements where some attributes are not defined?
  6. How to identify child elements?
  7. How to identify sibling elements?
  8. How to track user actions?

 

 

What is CSS? 

The Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation semantics (the look and formatting) of a document written in a markup language such as HTML or XML.

 

Sample CSS is shown below:

<style>
#flex-container {
display: -webkit-flex;
display: flex;
-webkit-justify-content: flex-end;
justify-content: flex-end;
width: 500px;
height: 200px;
background-color: Green;
}
#flex-item {
background-color: Silver;
width: 150px;
height: 130px; margin: 10px;
}
</style>

In CSS, there is a pattern-matching rule which determine style should be applied to elements in the DOM. These patterns are called css-selectors. Hence if all conditions in this css selector or pattern is true for a certain element, the selector matches the element and finally, the browser applies the defined style in CSS syntax. So for our previous css style this may look like below:

 

Css-example
Css-example

 

 

Note: For more information on CSS and CSS selectors, visit http://en.wikipedia.org/wiki/Cascading_Style_Sheets.

 

 

How Selenium Webdriver identifies elements using this CSS selector?

 

Selenium WebDriver uses exact same principle of CSS selectors or patterns to locate elements in DOM. This is why it is much faster and reliable when compared with XPath.

 

Now let’s see some basic examples on CSS selectors that can be used in Selenium WebDriver.In Selenium, the WebDriver’s By class provides the cssSelector() method for locating elements using CSS selectors.

 


To get the web elements with absolute path

 

Absolute paths refer to the very specific location of the web element considering the complete hierarchy in the DOM. For instance you may have : html>head>body>div>div”some web elements say input”

Let’s take an example here suppose you have a input field say Customer name.

WebElement customerName = driver.findElement(By.cssSelector("html body div div form input"));

 

 

Note: there should be space between the tags or else this will fail.

 

To get web elements using direct parent with absolute path

In case we are unable to succeed in previous example. Then we can use direct parent relationship to identify these elements. So all you need to do is put “>” greater than symbol after the tags.

This described the direct parent to child relationship with “>” as a separator:

 

WebElement customerName = driver.findElement(By.cssSelector("html >body > div > div > form > input"));

 

 

To get web elements using innerText() and textContent() Pseudo-Class

 

The CSS selectors provide the innerText() and textContent() pseudo-class which is used to check text presence of the specified text and return the found control.

 

For example, imagine we encounter a table with lots of data in it about customer and his details. In that case, we can search for text say “Details of customer 1”

 

WebElement cell = driver.findElement(By.cssSelector("td[textContent= ‘Details of customer 1’]"));

 

Or we can also use as:

WebElement cell = driver.findElement(By.cssSelector("td[innerText= ‘Details of customer 1’]"));

 

The innerText() or textContent() accepts the text to be searched and checks all the <td> elements in DOM for the specified text.

 

 

To get the web elements with relative path

The above two shown strategies are quite good in case you need to work on static forms or less frequent changing web pages.

But in case there is change in the structure or hierarchy of the elements on a page, then locator will fail to find the element. So what we can do here is we can then move with relative paths.

 

Using relative paths, we can locate any web element directly, irrespective of their location in the DOM.

 

For example, we can locate the customerName Input field in the following way,

WebElement customerName = driver.findElement(By.cssSelector("input"));

 

Note: The catch here is that we assume the input field to be the first in the form of that page.

 

 

Use the Class selector with relative path

 

We can also use the Class attribute to locate any element in conjunction with relative paths. This is pretty easy as it can be done just by specifying the type of HTML tag, then adding a dot followed by the value of the class attribute.

 

For instance let’s assume we have css class name “login” which gets applied to the input button post browser renders.

 

WebElement inputLogin = driver.findElement(By.cssSelector("input.login"));

 

 

Use ID selector with relative path

 

Similarly we can also use the IDs assigned to elements for identification. To use this method, we have to specify the type of HTML tag, then entering a hash followed by the value\ID of the Class attribute. So if we take same example from before of customerName it will be like this:

 

WebElement customerName = driver.findElement(By.cssSelector("input#customername"));

 

**Where tag is “input” and css class value is “customername”. This will return the customerName <input> element using its id attribute.

 


Use Attributes Name Selector

Now we will witness completely new approach where instead of specific attributes we will ask for attribute values. Take same example of input field we have been discussing so far, but now we will lookup for all similar controls or web elements. So to get any <input> elements which have “name” attribute specified, we will say

 

List<WebElement> allCustomerNames = driver.findElements(By.cssSelector("input[name]"));

 

For identifying web elements where some attributes are not defined then what should we do?

 

“This is cherry on top!” – we can specify a Boolean value with our matching pattern attribute in case we wish to find elements which are dynamic in nature, such that they have value and id’s defined but not names. This Boolean can be defined as  with a “not” pseudo-class to locate elements not matching the specified criteria.

 

So if we take same example as above then,

 

List<WebElement> allCustomerNames = driver.findElements(By.cssSelector("input:not([name])"));

 

This will return all the input elements not having “name” attribute defined in them.

 

What else can we do?

 

The other very interesting way around is to locate elements matching partial attribute values. This partial match method is very helpful when elements are dynamically generated and assigned values. Plus these values changes as per requests.

 

I would suggest you to follow and memorize below shared table:

Syntax Example Description
^= input[id^=’newinput’] It means “Starting with:”. For example, if the ID of an element is newinput-1, and so on. This will locate and return elements with ‘newinput’at the beginning of the ID.
$= input[id$=’_newinput] “It means Ending with:”. For example, if the ID for an element is a_1_newinput, this will locate and return elements with “_newinput” at the end of the ID.
*= Input[id*=’customerName’] It means “substring:”. For example, if the ID of an element is div_

login_customerName_textfield, this will use the customerName part in the middle to match and locate the element.

 

 

Use Advanced CSS selectors with Selenium

 

In this part, we will explore some advanced CSS selectors for locating elements where we will look at adjacent sibling combinators and pseudo-classes.

 

To get child web elements

 

We can again use parent child relationship discussed earlier but with some more details in it such that we acquire the target control or web element. Let’s take same example, to locate the customerName Field in the login form, we can use the following:

 

WebElement customerName = driver.findElement(By.cssSelector("form#loginForm> input"));

Similarly the nth-child() method can be used to get to the exact target child:

 

WebElement customerName = driver.findElement(By.cssSelector("form#loginForm :nth-child(2)"));

Here, the second element in <form>is the customerName field.

Similarly, we can also use first-child, last –child apart from nth-child(). The first two pseudo classes are self-explanatory.

 

To get the sibling web elements

 

The other very interesting part with css selectors is that we can locate sibling elements using the + operator. For example, imagine on the sample page there is paragraph  <p>element with Details of Customer 1 text is selected in the following way:

 

WebElement customerDetails = driver.findElement(By.cssSelector("div#top1 > p + p"));

In this example, the first child of div#top1 will be <p> with  “Title” text,and its immediate sibling will be Details of Customer 1.

 

Here are few more adjacent sibling combinators for locating siblings:

P + P div#top1 > p + p Immediately following sibling. This will locate Details of Customer 1.
p + * + p

 

div#top1 > p + * + p Following sibling with one intermediary.

This will locate Details of Customer 1.

 

 

Can we track user actions too? Yes, use user action pseudo-classes.

 

Interestingly, there are some more pseudo classes like “ :focus”,”:hover”,”:active”. Let’s see same example as above in the following way:

 

WebElement customerDetails = driver.findElement(By.cssSelector("input:focus"));

This will locate any element that currently has the input focus. Similarly we can use hove and active.

 

The following table describes these in detail:

Pseudo-class Example Description
:enabled input:enabled This will locate all the elements that are enabled for user input.
:disabled input:enabled This will locate all the elements that are disabled for user input.
:checked input:checked This will locate all the elements that are checked for checkboxes.

 


Conclusion

Selenium WebDriver interface is quite well acquainted with CSS Selectors to aid in identification of controls whether static or dynamic. We have covered right from single control identification to list of controls, returning where control’s attributes are missing, or user action tracking is required.

Now we will move towards the most discussed topic in interviews which is XPath.

This brings us to the end of our discussion on “How to find web elements using CSS Selectors?”. Now we will see how we can find elements using XPath?

 


I really hope you have enjoyed reading the post. If you have any doubt on this please feel free to add your comment below.

If you would like to keep track of further articles on Selenium. I recommend you to SUBSCRIBE by Email and have new Selenium articles sent directly to your inbox.

 

 

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

advanced-floating-content-close-btn
https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5034726663464946 (adsbygoogle = window.adsbygoogle || []).push({});
advanced-floating-content-close-btn 
*************************** Do you want to learn TOSCA? Do you want to excel in Career? Try my New Courses: 1. Tricentis Tosca and Working with Excel   2. Tricentis Tosca and UI Automation Great News!!   Price has been slashed down for limited period of time.So Hurry!!! Click The Shown Links and Enjoy Learning. ***************************
 
error: Content is protected !!