Meaghan Lewis discusses the pros and cons of locators to determine which will be the best to use in Selenium tests. In addition, Meaghan talks about the power of CSS Selectors and shows examples of how to use them in conjunction with other locator types.
- [Instructor] There are various ways to locate elements to find an HTML using the attributes class name, CSS selector, ID, link text, name, tag name, and XPath. With all these locators, there are usually numerous ways to find an element. And even though all these locator strategies exist to help locate an element, it doesn't mean that all of these options are the best choice to use. Some locators are better than others.
The best locators are those that are unique, descriptive, and static or unlikely to change. I typically avoid using the following locators, link text which works as long as links are unique on a page, tag name which is usually not unique or descriptive, and XPath which is definitely not descriptive. I prefer using ID, class, name, and CSS selector all of which are usually unique, descriptive, and static.
There is one locator that is the most powerful and that is CSS selectors. A CSS selector can be used in conjunction with all the other types of locators and more. Using CSS selectors allows for a lot of flexibility and are great for even the most hard-to-find elements. I'll show a few examples now. Say we want to find an element using its ID and take for example the following HTML where there is an input tag with an ID, class, and name all with a value of q.
An ID can be represented with the hash symbol in CSS so to find that, I can specify driver.findElement(By.cssSelector('#q')). Say we want to find an element using class. I have the same HTML here with an input tag and an ID, class, and name all of q. A class can be represented with a dot so driver.findElement(By.cssSelector('.q')) will help find the class name.
Any other locator can be found by defining the tag name and then specifying the locator in the value. So let's take that same sample of HTML and say I want to find the name. What I can do is say driver.findElement(By.cssSelector) and I have the tag name and then in brackets the name and then is equal to q which is the value there and that will allow me to be able to find any other locators. The CSS selector can also be used for even more advanced things like finding based on substring or string, using wildcards, and child and sibling nodes.
In the rest of this chapter, I'll show examples for how to use advanced CSS selectors and automation.
- Using browser drivers and WebDriver
- Inspecting elements
- Selecting a locator
- Combining multiple CSS attributes
- Using common components
- Implicit and explicit waits
- Automating workflows
- Testing behaviors
- Using page objects
- Connecting to GitHub
- Running on the grid
- Using cloud-based testing tools