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>
2. Accessing by class
3. Accessing child through parent
<form id=’registration’ action=”/registration_page.php”>
<div for=”fname”>First name:</div>
<input type=”text” value=”fname”>
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”>
5. For accessing elements with the child-child-parent relationship
<li id=’first list’>
Selecting a tag
6. For accessing the nth-of-type element
Therefore, ul#categories>li:nth-of-type(n) → all elements
7. For accessing sibling element
8. For accessing element via the help of not operator
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 email@example.com