Advanced CSS Selectors in Automation Testing

Irwan Syarifudin
3 min readNov 30, 2023

--

https://scrapfly.io/blog/content/images/parsing-html-with-css_banner.png

Intro

Welcome to the dynamic realm of automation testing, where precision and reliability are the cornerstones of success. As automation testers, we often find ourselves navigating through complex web applications, meticulously crafting scripts that need to withstand the ever-evolving landscape of app.

On this journey based on my knowledge and experience, the power of CSS selectors has been a guiding light, allowing us to define and interact with elements with surgical precision. While basic CSS selectors can serve us well in many scenarios, there are times when the demands of powerful automation scripts require more advanced tools.

In this bit of comprehensive guide to start your journey into advanced CSS selectors, and this guide isn’t just about writing selectors but it’s about empowering our scripts to handle the intricacies of modern web applications with finesse.

disclaimer: this example using method findElement(By) Javascript with selenium to interact with elements. But, whatever language/framework defines the elements it’s the same applies

Section 1: Basic CSS Selectors Recap

Element by ID:

findElement(By.id('#myElement')

Element by Class:

findElement(By.className('myElement')

Element by CSS Selector

findElement(By.css('.myElement')

Section 2: Advanced Selectors for Automation: A Deep Dive

2.1 Combining Selectors:

> Descendant element

findElement(By.css('div p')

> Child element

findElement(By.css('.parent > span')

> Adjacent Sibling Combinator

findElement(By.css('h2 + p')

> General Sibling Combinator

findElement(By.css('h2 ~ p')

2.2 Pseudo-Classes and Pseudo-Elements:

Pseudo-Class (:nth-child)

findElement(By.css('h2 ~ ul li:nth-child(odd)')

2.3 Attribute Selectors:

Attribute Starts With Selector

findElement(By.css('[data-custom-attribute^="value"]')

Attribute Ends With Selector

findElement(By.css('a[href$=".pdf"]')

Attribute Contains Selector

findElement(By.css('input[type*="text"]')

2.4 Structural Selectors:

:not() Pseudo-Class

findElement(By.css('ul li:not(.special)')

:nth-of-type Selector

findElement(By.css('ul li:nth-of-type(3)')

:nth-last-of-type Selector

findElement(By.css('ul li:nth-last-of-type(2)')

2.5 Dynamic Content Selectors:

:checked Pseudo-Class

findElement(By.css('.testing input[type="checkbox"]:checked')

Tips: Practical Examples for Automation Testing

  • Do and do practice with real-world for each category of advanced selectors, like include scenarios like form validation, table interaction, and navigation.

Here are several website references for practice:

--

--