Selenium locator chaining

Today, we are going to discuss the core ingredients of a successful Selenium automation project. Secondly, we have to select the locators on a case by case basis. We need to use them wisely as the situation demands.

This change directly impacts our test automation and the usage of locators. The changes would undoubtedly lead to breaking some of the locators used in the project. You must keep a Selenium locator as short as possible.

Selenium Find Element By Text Tutorial with Examples

It would make your code cleaner, reduce complexity and help in the long-term maintenance of the project. The requirement is like to have a div id which gets changed with every build. And the developer adds a timestamp to the div id. You can verify this from the below HTML example. The Html contains a fixed class, but the id here is dynamic and bears the timestamp of the build.

So, we have to select a locator that can manage the variable part of the id. In the next statement, you would figure out the real power of the XPath locator. The proposed solution to access the element with variable id is available below.

There is no second thought about the degraded quality of the above locator. Any minor change in the chain of its elements is sufficient to lead to an incorrect result. The HTML code given below would help to understand more about the problem. How to handle the chain of locators? What would you do to make your locators work when Html element losses one of its properties. You need to devise a locator strategy which is independent of the locator attributes.

It is because checking for the additional classes would yield you no benefit. Instead, your code would break when any of these two properties gets changed. XPath expression — Recommended. We hope that this Selenium tutorial would have helped you in doing that. XPath expression — Not recommended.By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service. The dark mode beta is finally here. Change your preferences any time.

Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. I am using Selenium to test a website, does this work if I find and element by more than one criteria? No it does not. This is not valid anyway. However, you can write the selectors such a way that will cover all the scenarios and use that with findElements. There are lots of information if you search for CSS selectors. Learn more. Asked 4 years, 11 months ago.

Active 2 months ago. Viewed 24k times. I too have wondered this and find it daft that chaining isn't supported. Active Oldest Votes. Saifur Saifur It's just the way of using multiple condition. To combine By statements, use ByChained: driverChrome. George George 91 1 1 silver badge 7 7 bronze badges.

Using XPath to Locate Web Elements - in very detail

CSS Selectors would be perfect in this scenario.Actually, many web pages do not use the slider or the text box but both of them as in the following image:. Here, the user has plenty of options for changing the price:.

The current slider position corresponds to a value. Use the Actions class to build the list of actions to be done on the slider. The price is stored in the value attribute of the hidden element. Use the Keys. The sequence includes the price value and the tab key. The slider percentage is stored in the style attribute of the slider element.

Like Like. Good one. Thanks for sharing various different test cases. Would have been better if some real site example is taken as it helps. You are commenting using your WordPress. You are commenting using your Google account. You are commenting using your Twitter account.

Do not store element locators in property files

You are commenting using your Facebook account. Notify me of new comments via email. Notify me of new posts via email. Skip to content learn Selenium WebDriver 2 Comments. Sliders allow users to select a value by dragging and dropping a handle. This value can be a price, a quantity, a year. The web page could use a textbox for getting the same information from users. But with sliders, the page becomes much more interesting. Actually, many web pages do not use the slider or the text box but both of them as in the following image: Here, the user has plenty of options for changing the price: drag and drop the slider handle click the plus button multiple times input the price in the textbox; the slider will update itself to match the new price The slider stores its current position as percentage at all times.

So, for a typical slider, we can have 4 different elements. The tab key is needed for updating the slider. Like this: Like Loading Would have been better if some real site example is taken as it helps Like Like Reply. Leave a Reply Cancel reply Enter your comment here Please log in using one of these methods to post your comment:. Email required Address never made public.By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service.

The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. I am very confused with what the documentation for ByChained class mentions. It says:. Mechanism used to locate elements within a document using a series of other lookups.

selenium locator chaining

This class will find all DOM elements that matches each of the locators in sequence, e. There is also an issue for selenium on code. I don't get it. Why should by1 and by2 be locators of two different elements? When I initally came across this class I felt that it will help in locating element s by using different locators. So that if one locator does not work, the next would work.

But when I practically used this class it behaved very weirdly and threw NoSuchElementException all the time. I want to find the input field by using two locators in ByChained: 1.

selenium locator chaining

I was expecting that if my first By did not work, then it will find the element with the next By in the series. Can someone please explain how this class works with an example and in which scenarios it could be used?

You can use the ByChained by to specify that you want that element by doing the following:. What happens is that it finds the first element then searches underneath that in the dom heirarchy for the selector that comes next in the list. Basically this By is just a nice clean way of no longer having to do the following:. Your request would be satisfied by something that could be called ByAny which would return elements that match any of the passed By arguments. However, ByChained works differently.

It finds the elements that are matched by the first argument, then searches their descendants using the second argument etc. So, if you had HTMl like this:. Note that there also is a ByAll class that searches for elements matched by all of the By arguments passed.

It's probably important to note because I never see anyone mention this that ByChained should be used just like any other By locator, like so:. Learn more. How Selenium's ByChained class really works? Ask Question. Asked 6 years, 1 month ago. Active 5 years, 2 months ago.Given how little it takes for UI testing to crumble into maintenance hell, having a good locator strategy is a must.

So if you intend to automate UI testing with Selenium, scan through the best practices outlined in this post. A best practice that deserves mentioning in this context is less technical, yet it will save you tons of time. Dynamic IDs generated by web development frameworks will change with every page load, which renders them useless. One way to do this is via CSS:. One thing to watch out for with this locator are other element sharing an ID with the same stable part e.

One of Selenium best practices for locators is to always look for unique stuff. Neither name tags nor links and link text are inherently unique, but they may be unique under certain conditions. Have a look at the example below:. The folks at 3Qi Labs came up with a neat illustration for this best practice for Selenium locators. The illustration is called the Locator Tree of Life:. You start with an ID, and, if that option is unavailable, resort to name attributes, links, link texts, etc.

Immediate parents and children are relatively future-proof; grandparents and grandchildren are still acceptable. Anything that requires a lengthier chain of relatives will probably break before you know it. Whenever possible, choose an ancestor or descendant that has a unique ID. In fact, targeting an element via a grandparent with an ID will often prove a smarter solution than using an immediate parent with non-unique attributes. Moreover, it will most probably prove a wiser tactic than directly targeting the element without an ID.

Targeting the button from the example above by all class values i. Targeting just one of the classes, on the other hand, will result in a more robust locator:.

Element locators

Being able to keep all locator types in memory is an awesome skill, but very few of us can actually pull this of. For this reason, having a good cheat sheet is always handy. IDs might seem like a robust option, but they often get renamed, copied, or simply deleted.

Anything other than an ID-based locator has even less chance of living through the complete development cycle. So what can you do about? One way to improve locator reliability is by developing a fail-safe lookup algorithm. This algorithm would encapsulate element locators in a class shared by all tests while providing some recovery logic in there.

For example, if you are looking up an element without an ID, there is a good chance your locator will fail because the attribute has changed.

Rather than failing the lookup and the test, the lookup algorithm will attempt to find the closest matching element based on other stored selectors. Sure, this may lead to unintended consequences if the algorithm produces false positives. On the other hand, you can reduce the probability of false positive by storing enough data about the element.

And the really great part is it provides this fail-safe algorithm out of the box. Instead of merely recording UX sessions and spewing out autogenerated WebDriver code like most IDEs doScreenster provides you with editable codeless test steps. When you record a test, the platform creates a full list of locators for each UI element.In this case, the test opens the site, searches for a keyword and then finds the title of the first result.

If the code generates an exception when trying to find the title element, is the error about the title not being available or about the first result? What if you need to find an element included in another element included in another element included in another element? The object gets 2 parameters in the constructor for the locators of the parent and child elements.

There are no additional WebElements that should be created and the code stays approximately the same size. However, if you are interested in better and more detailed learningthis Kindle ebook will help you improve your Selenium code:. Like Like. So find the first item of the page that does not change. Now within find the first table, then the first row, the first cell and the first image. You are commenting using your WordPress.

You are commenting using your Google account. You are commenting using your Twitter account. You are commenting using your Facebook account. Notify me of new comments via email. Notify me of new posts via email. Skip to content learn Selenium WebDriver 3 Comments. Have you ever had to find an element in another element?

Of course you have. How did you do it? Maybe you used a locator that searches for the parent element first and then for the child element in the parent. This seems like a decent approach but is it not. Since the locator combines both, it would be difficult to know. We can change the code so that the parent element is found first and stored in a WebElement variable.

selenium locator chaining

When the code works this way, in case of an error, it is very clear which element caused it. This is better than before but it extends poorly. For each parent element, you need to search for the element and store it in a variable. Which leads to lots of duplication. This duplication can be removed using the ByChained Selenium class. Finding the element happens as follows: the element for the 1st locator is searched the element for the 2nd locator is searched in the first element Using this approach scales well even if we have elements included in many other elements.

Tips and tricks are great. Keep coming to this blog for more. Like this: Like Loading Leave a Reply Cancel reply Enter your comment here Please log in using one of these methods to post your comment:.If you wish to learn the easiest way to locate elements on a webpage, then you have landed at the perfect place.

Locating elements is indeed a nightmare because of the complexity of finding the web elements in the webpage and automating them. To simplify this task, we use something known as locators in Selenium. In this article, I will give you a brief insight into the different types of locators along with relevant examples.

Locator s are defined as an address that identifies a web element uniquely within the webpage. Finding correct GUI elements is a prerequisite for creating an automation script but, accurate identification of GUI elements is much more difficult than it sounds.

Sometimes, you might even end up working with incorrect GUI elements or no elements at all! Hence, using the right locator ensur es that the tests are faster, more reliable or has lower maintenance over releases.

But there will be times when choosing the right locator will become a nightmare because of the complexity of finding the web elements in the webpage. There is a diverse range of web elements like text box, id, radio button etc. It requires an effective and accurate approach to identify these elements. In order to identify web elements accurately and precisely, selenium makes use of different types of locators. They are as follows:. The most popular way to identify web element is to use Id.

For example — the employee Number or Account which will be unique. I will launch Google Chrome and navigate to yahoo. Here, I will try to locate the email text box using ID Locator.

On inspecting the above web element, you can see it has an input tag and attributes like class and id. Now, I will use the value of Id locator i.

selenium locator chaining

You can refer below image for the output:. I hope this gives you a clear understanding of how Id locator in Selenium works. With this strategy, the first element with the value of the name attribute will be returned. The difference here is that you should use a name instead of id. You can identify the hyperlinks on a web page using linkText. In order to create the hyperlinks on a web page, you can use anchor tags followed by the linkText.


thoughts on “Selenium locator chaining”

Leave a Reply

Your email address will not be published. Required fields are marked *