Selenium CSS Selectors Examples


Writing Selenium CSS Selectors for object locating alone cannot improve script execution performance. Additionally you need to write performant CSS Selectors. Copying and pasting CSS Selectors that are suggested by any plugin or browser is not a right approach. You should be able to construct your own CSS Selectors or should possess strong knowledge of auto generated selectors.

In this blog article, you will learn the basics of Selenium CSS Selectors. If you are familiar with XPath and CSS Selector construction on your own, then creating robust automated test suite will be a cake walk.

By IDIf you have ID for an element on which you are going to perform action, then you can go with ID selector instead of CSS Selector. However, if you want to identify parent node in the CSS Selector, then you should be familiar with selecting an element using ID.

HTML

<input type="text" id="txt1"/>

Selector

#txt1

Direct ChildYou can use the below CSS Selector to select a direct child under a parent node.

HTML

<div>
<input type="text" />
</div>

Selector

div>input

Adjacent SiblingOnce you select a node, you can also jump to an adjacent sibling using the below selector.

Selector

div > input + input
Selenium CSS Selectors

Starts WithUsing starts with to match attribute value.

HTML

<input type="text" id="txt4" class="textbox-st"/>

Selector

input[class^='text']

Sub String MatchMatching a sub string in an attribute value.

HTML

<input type="text" id="txt4" class="textbox-st"/>

Selector

input[class*='box']

Ends WithUsing ends with to match attribute value.

HTML

<input type="text" id="txt4" class="textbox-st"/>

Selector

div>input[class$='st']

nth-childSelecting an element using its index

Selector

tr:nth-child(4)
CSS Selector Selenium

In conclusion

Basics of Selenium CSS Selector and XPath is a mandatory skill for a test automation engineer. As a software testing services provider, we train all our new recruits on object locating techniques. When your team is well versed in XPath & CSS Selector, they will be able to produce robust test automation suites.


Leave a Reply

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