Selenium Tips: CSS Selectors
Sauce AI for Test Authoring: Move from intent to performance in minutes.|xBack to ResourcesBlogPosted<
Sauce AI for Test Authoring: Move from intent to performance in minutes.
|
x
Blog
Selenium Tips: CSS Selectors
Learn about CSS rules and pseudo-classes to help you move your XPATH locators to CSS.
In order for or to click on an element, eccentric into it, or mouse in or out, the instrument first require to find the element. The WebDriver code library ply methods to do just that, such as findelement () or findelements (). These unremarkably take a locator, which can be created by ID, XPATH Code, or Cascading Style Sheets (CSS). can be as easy as choose the factor in developer tools or using something likeChropath. Fundamentally, XPATH is a query language for XML-like documents, such as web page. It can be awkward to publish, brittle, and even more awkward to reverse technologist. As a result, CSS has gained favor as the way to name aim in WebDriver.
Like most powerful things, CSS has a bit of a learning bender. It & # x27; s certainly a lot more challenging than cut and pasting from a tool. Yet if you indue the time in l, you can have more powerful bindings that are easier to read, less unannealed, and slightly more intimately integrated into the browser program.
Today we & # x27; ll provide CSS rules, tip, and pseudo-classes to either get you out on the right pes, or, maybe help you move your XPATH locators to CSS.
Getting Started with CSS Selectors
A CSS Selector is a combination of an element selector and a value which identifies the web element within a web page. They are string representations of HTML tags, dimension, Id and Class. As such they are patterns that gibe against elements in a tree and are one of various technology that can be used to select node in an XML document.
Today we & # x27; ll cover elementary CSS selectors, then more advanced, then pseudo-classes, which are fundamentally powerful, built-in matching functions that reduce a search to just what you are looking for.
I: Simple
Id
An ingredient ’ s id in XPATH is delineate using: “ [@ id= & # x27; example & # x27;] ” and in CSS using: “ # ” - ID & # x27; s must be alone within the DOM.
Examples:
1XPath: //div [@ id= & # x27; illustration & # x27;]2CSS: # example
Element Type
The previous example showed //div in the xpath. That is the factor type, which could be input for a text box or push, img for an image, or & quot; a & quot; for a link.
1Xpath: //input or2Css: =input
Direct Child
HTML pages are structured like XML, with children nested inside of parents. If you can locate, for example, the first tie-in within a div, you can construct a twine to reach it. A direct fry in XPATH is delimit by the use of a “ / “, while on CSS, it ’ s defined using “ & gt; ”.
Examples:
1XPath: //div/a2CSS: div & gt; a
Child or Sub-Child
Writing nested divs can get tiring - and result in code that is brittle. Sometimes you ask the code to change, or need to skip layers. If an elementcouldbe inside another or one of its nestling, it ’ s define in XPATH using “ // ” and in CSS precisely by a whitespace.
Examples:
1XPath: //div//a2CSS: div a
Class
For class, things are somewhat similar in XPATH: “ [@ class= & # x27; example & # x27;] ” while in CSS it ’ s just “. ”
Examples:
1XPath: //div [@ class= & # x27; model & # x27;]2CSS: .examplePro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.
II: Modern
Next Sibling
This is useful for navigating lists of elements, such as forms or ul items. The next sibling will tell selenium to find the adjacent conterminous element on the page that ’ s inside the same parent. Let ’ s show an example apply a shape to select the field after username.
1<form class=& quot; form-signin & quot; role =& quot; form & quot; action =& quot; /index.php & quot; method =& quot; billet & quot;>2<h4 class=& quot; form-signin-heading & quot;></h4>3<input type=& quot; text & quot;class=& quot; form-control & quot; id =& quot; username & quot; name =& quot; username & quot;procurator=& quot; username & quot;required autofocus></br>4<input type=& quot; watchword & quot;class=& quot; form-control & quot; id =& quot; password & quot; name =& quot; password & quot;placeholder=& quot; password & quot; required>5<p>6<button class=& quot; btn btn-lg btn-primary btn-block radius & quot; type =& quot; submit & quot; name =& quot; login & quot;>Login</button>7</form>
Let ’ s write an XPath and css selector that will choose the input battleground after “ username ”. This will select the “ alias ” remark, or will select a different constituent if the sort is reordered.
1XPATH: //input [@ id= & # x27; username & # x27;] /following-sibling: input [1]2CSS: # username + input
Attribute Values
If you don ’ t care about the ordering of child elements, you can use an attribute selector in selenium to choose elements based on any attribute value. A good model would be choosing the ‘ username ’ element of the form above without add a stratum.
We can easily select the username ingredient without adding a class or an id to the ingredient.
1XPATH: //input [@ name= & # x27; username & # x27;]2CSS: input [name= & # x27; username & # x27;]
We can even concatenation filter to be more specific with our selectors.
1XPATH: //input [@ name= & # x27; login & # x27; and @ type= & # x27; submit & # x27;]2CSS: input [name= & # x27; login & # x27;] [type= & # x27; submit & # x27;]
Here Selenium will act on the stimulation battlefield with name= & quot; login & quot; and type= & quot; submit & quot;
Choosing a Specific Match
CSS chooser in Selenium allow us to voyage lists with more delicacy than the above methods. If we have a ul and we want to take its fourth li element without regard to any former elements, we should use nth-child or nth-of-type. Nth-child is a pseudo-class. In straight CSS, that allows you to reverse doings of sure factor; we can likewise use it to select those ingredient.
1<ulid="recordlist">2<li>Cat</li>3<li>Dog</li>4<li>Car</li>5<li>Goat</li>6</ul>
If we require to select the fourth li element (Goat) in this inclination, we can use the nth-of-type, which will find the fourth li in the tilt. Notice the two colon, a recent alteration to how CSS name pseudo-classes.
1CSS: # recordlist li: :nth-of-type (4)
On the early hand, if we require to get the fourth element only if it is a li element, we can use a filtered nth-child which will select (Car) in this case.
1CSS: # recordlist li: :nth-child (4)
Note, if you don ’ t specify a child type for nth-child it will grant you to select the fourth child without attentiveness to type. This may be useful in testing css layout in selenium.
1CSS: # recordlist *: :nth-child (4)
In XPATH this would be similar to using [4].
Sub-String Matches
CSS in Selenium has an interesting feature of allowing partial string match using ^=, $ =, or * =. I ’ ll delimitate them, so show an example of each:
1^= Match a prefix2CSS: a [id^= & # x27; id_prefix_ & # x27;]34A link with an “ id ” that starts with the text “ id_prefix_ ”56$ = Match a suffix7CSS: a [id $ = & # x27; _id_sufix & # x27;]89A link with an “ id ” that ends with the textbook “ _id_sufix ”1011* = Match a substring12CSS: a [id * = & # x27; id_pattern & # x27;]1314A link with an “ id ” that contains the schoolbook “ id_pattern ”15
Pseudo Class Compatibility
An earlier version of this clause references: contains, a powerful way to couple element that had a desired inner text block. Sadly, that lineament is deprecated and not support any longer by the W3C Standard. The currentCSS Selectors level 3 criterionis implemented by all major browsers; tier 4 is in working draught mode. That standard document has a elaborate lean of selectors and pseudo-classes. For a more manageable listing, look at theMozilla Documentationwhich has a wonderful, accomplished list ofpsuedo classes. Drill into any pseudo-class and scroll down for specific information on compatibility in different browsers, include this example from the nth-child () pseudo-class.

Related resources
Share this post
Ready to start quiz with Selenium and Sauce Labs?
Let & # x27; s go!
Automate This With SUSA
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.
Try SUSA FreeTest Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free

