Automation Secrets, cheat sheet to CSS selectors
When an HTML page is loaded in the web browser, it becomes a document object, and all its HTML, head, title, body, h1, p, img, div, span, a, form, button, tags become objects.
For front-end automation, these objects are identified as elements. Selenium provides APIs to perform various actions on these elements. Therefore identifying these elements uniquely is very important.
Now the identification part can be done by two tools
- By finding the Xpath ID of the elements
- By CSS Selectors
Both are powerful tools, however, some things are more effortless to express with CSS selectors and others are easier to express with XPath ID. Initially, XPATH is a query language for XML-like documents, such as web pages. It can be difficult to find, write, and even to reverse engineer. As a result, CSS has drawn favor as the way to identify objects in WebDriver.
The following are the built-in matching functions that come with using CSS selectors
- Accessing by Id
<div id=’userName’> Full Name</div>
Therefore, div#userName
2. Accessing by class
<div class=’row’>
Therefore, div.row
3. Accessing child through parent
<form id=’registration’ action=”/registration_page.php”>
<div for=”fname”>First name:</div>
<input type=”text” value=”fname”>
<input type=”submit”>
</form>
Therefore, #registration>div will return direct div (child) to form (parent)
Therefore, #registration div will return div (child) to form (parent)
4. For accessing space-separated values.
We need to remove spaces and replace them with ‘.’
<input class=”pro-12 max-34r Global”>
Therefore, input.pro-12.max-34r.Global
5. For accessing elements with the child-child-parent relationship
<ul id=’categories’>
<li id=’first list’>
<a>
</li>
</ul>
Selecting a tag
Therefore, ul#categories>li#first.list>a
6. For accessing the nth-of-type element
Therefore, ul#categories>li:nth-of-type(1)
Therefore, ul#categories>li:nth-of-type(n) → all elements
7. For accessing sibling element
<div class=’wrapper-form’></div>
<div id=’whole-form’></div>
Therefore, div.wrapper-form+div#whole-form
8. For accessing element via the help of not operator
Therefore, input.form-control:not(.login-password)
9. For accessing element via other attributes such as style, type, name, src, test-id, etc
Therefore, htmltag[attr1=’value’] → CSS with one attribute
Therefore, htmltag[attr1=’value’][attr2=’email’] → CSS with two attributes.
Feel free to connect on jagriti.10sharma@gmail.com
Cheerio!!