CSS Attribute Selectors

Introduction

CSS Attribute Selectors allow Selenium to locate web elements based on the values of their HTML attributes such as name, type, placeholder, title, and many others. They provide a flexible and readable way to identify elements when unique IDs are unavailable or when attributes offer more reliable locators.

CSS Attribute Selectors are widely used in Selenium automation frameworks because they create maintainable and easy-to-read locators for modern web applications.

In this tutorial, you’ll learn what CSS Attribute Selectors are, why they are used, different types of attribute selectors, practical examples, real-world use cases, common mistakes, and best practices.


What are CSS Attribute Selectors?

A CSS Attribute Selector identifies an element based on one or more HTML attribute values.

For example, consider the following HTML:

<input type="password" name="password">

The element can be located using either its type attribute or its name attribute.


Why Use CSS Attribute Selectors?

CSS Attribute Selectors are useful because they:

  • Locate elements using HTML attributes.

  • Work well when ID locators are unavailable.

  • Create clean and readable locators.

  • Improve framework maintainability.

  • Support flexible element identification.

  • Are widely used in modern automation frameworks.


Syntax

Exact Attribute Match

driver.find_element(
    By.CSS_SELECTOR,
    "[attribute='value']"
)

Types of CSS Attribute Selectors

1. Exact Match (=)

Selects an element whose attribute exactly matches the specified value.

[name='username']

2. Starts With (^=)

Selects elements whose attribute value starts with a specific text.

[id^='user']

3. Ends With ($=)

Selects elements whose attribute value ends with a specific text.

[id$='name']

4. Contains (*=)

Selects elements whose attribute value contains a specific text.

[class*='button']

Example

The Login page contains elements with various HTML attributes such as name, type, and submit.

The Selenium code is:

from selenium import webdriver
from selenium.webdriver.common.by import By


# Topic: 12. CSS Selectors - CSS Attribute Selectors
# Practice site: https://the-internet.herokuapp.com/login
# Run: pytest -s 12_examples/test_02_css_attribute_selectors.py
#
# Attribute selectors target elements by attribute values such as type, name,
# or placeholder.


def test_css_attribute_selectors():
    driver = webdriver.Chrome()

    try:
        driver.get("https://the-internet.herokuapp.com/login")

        username = driver.find_element(
            By.CSS_SELECTOR,
            "input[name='username']"
        )

        password = driver.find_element(
            By.CSS_SELECTOR,
            "input[type='password']"
        )

        submit = driver.find_element(
            By.CSS_SELECTOR,
            "button[type='submit']"
        )

        assert username.is_displayed()
        assert password.is_displayed()
        assert submit.is_displayed()

    finally:
        driver.quit()

Output

The Username textbox,
Password textbox, and
Login button are located
successfully using CSS
Attribute Selectors.

Understanding the Code

Import the By Class

from selenium.webdriver.common.by import By

Imports Selenium’s locator strategies.

Open the Login Page

driver.get(
    "https://the-internet.herokuapp.com/login"
)

Launches the practice website.

Locate the Username Field

driver.find_element(
    By.CSS_SELECTOR,
    "input[name='username']"
)

Locates the Username textbox using its name attribute.

Locate the Password Field

driver.find_element(
    By.CSS_SELECTOR,
    "input[type='password']"
)

Locates the Password textbox using its type attribute.

Locate the Login Button

driver.find_element(
    By.CSS_SELECTOR,
    "button[type='submit']"
)

Locates the Login button using its type attribute.

Validate the Elements

assert username.is_displayed()
assert password.is_displayed()
assert submit.is_displayed()

Verifies that all three elements are present and visible on the webpage.


How CSS Attribute Selectors Work

        Python Script
               │
               ▼
        By.CSS_SELECTOR
               │
               ▼
       Read Attribute Value
               │
               ▼
      Search Matching Element
               │
               ▼
          Locate Element
               │
               ▼
         Perform Validation

Practical Example

Suppose you’re automating a Login page.

The Username textbox contains the following HTML attribute:

<input name="username">

Instead of using XPath, Selenium uses:

input[name='username']

to locate the Username textbox and perform validations successfully.


Automation Testing Example

Consider an online banking application.

The Login form contains:

<input type="password">
<button type="submit">

Selenium uses:

input[type='password']

and

button[type='submit']

to validate the Password field and Login button before performing authentication-related test cases.


Real-World Example

Automation engineers frequently use CSS Attribute Selectors for locating:

  • Username textboxes.

  • Password fields.

  • Search boxes.

  • Login buttons.

  • Registration forms.

  • Email fields.

  • Payment forms.

  • Custom UI components.

  • Elements containing data-testid, title, placeholder, and aria-label attributes.

These selectors are especially useful when IDs are unavailable or dynamically generated.


Advantages of CSS Attribute Selectors

  • Clean and readable syntax.

  • Flexible element identification.

  • Easy to maintain.

  • Faster than many XPath expressions.

  • Supports multiple attribute matching techniques.

  • Widely used in modern Selenium automation frameworks.


Limitations of CSS Attribute Selectors

  • Cannot locate visible text directly.

  • Dynamic attribute values can make locators unstable.

  • Incorrect attribute selection may return multiple matching elements.

  • Requires familiarity with CSS Selector syntax.


Common Mistakes Beginners Make

Using the Wrong Attribute Name

Incorrect

driver.find_element(
    By.CSS_SELECTOR,
    "input[user='username']"
)

Correct

driver.find_element(
    By.CSS_SELECTOR,
    "input[name='username']"
)

Using Dynamic Attribute Values

Avoid using attributes whose values change after every page refresh or deployment.

Choosing Non-Unique Attributes

If multiple elements share the same attribute value, Selenium may locate an unintended element.

Always prefer unique and stable attribute values whenever possible.


Best Practices

  • Prefer stable and unique HTML attributes.

  • Use exact attribute matching whenever possible.

  • Verify selectors using browser Developer Tools.

  • Keep CSS selectors simple and readable.

  • Avoid dynamic attribute values whenever possible.

  • Write maintainable and reusable locators within automation frameworks.


Conclusion

CSS Attribute Selectors provide a flexible and maintainable way to locate web elements using their HTML attributes. They are extensively used in Selenium automation because they create clean, readable, and reliable locators for modern web applications.

Understanding CSS Attribute Selectors is an important step toward mastering advanced CSS Selector techniques and building scalable automation frameworks.


Frequently Asked Questions (FAQs)

What is a CSS Attribute Selector?

A CSS Attribute Selector locates an element using one or more HTML attribute values.

What is the syntax for an exact attribute match?

driver.find_element(
    By.CSS_SELECTOR,
    "[attribute='value']"
)

What is the difference between =, ^=, $=, and *=?

  • = → Exact attribute value.

  • ^= → Starts With.

  • $= → Ends With.

  • *= → Contains.

Can CSS Attribute Selectors locate visible text?

No.

CSS Attribute Selectors work only with HTML attributes and cannot locate elements using visible text.

When should I use CSS Attribute Selectors?

Use them when ID locators are unavailable and the element contains unique and stable HTML attributes.


Key Takeaways

  • CSS Attribute Selectors locate elements using HTML attributes.

  • Use By.CSS_SELECTOR with attribute expressions to identify web elements.

  • Exact (=), Starts With (^=), Ends With ($=), and Contains (*=) are the most commonly used attribute selectors.

  • CSS Attribute Selectors are widely used in Selenium automation frameworks.

  • Prefer stable and unique attribute values for reliable automation.

  • Keep selectors simple, readable, and easy to maintain.

  • CSS Attribute Selectors help create scalable and maintainable Selenium automation solutions.