Bird
Raised Fist0
Selenium Pythontesting~15 mins

CSS attribute selectors in Selenium Python - Build an Automation Script

Choose your learning style10 modes available
Verify search input field using CSS attribute selector
Preconditions (2)
Step 1: Locate the search input field using a CSS attribute selector for input elements with type='search'
Step 2: Enter the text 'Selenium testing' into the search input field
Step 3: Submit the search form by pressing Enter key
Step 4: Wait for the search results page to load
✅ Expected Result: The search results page is displayed and the URL contains the search query 'Selenium testing'
Automation Requirements - Selenium with Python
Assertions Needed:
Verify the search input field is found using CSS attribute selector
Verify the search input field accepts the text input
Verify the page URL contains the search query after submission
Best Practices:
Use explicit waits to wait for elements and page load
Use By.CSS_SELECTOR with attribute selector syntax
Avoid hardcoded sleeps
Use clear and descriptive variable names
Automated Solution
Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Initialize the Chrome driver
with webdriver.Chrome() as driver:
    driver.get('https://example.com')  # Replace with actual homepage URL

    wait = WebDriverWait(driver, 10)

    # Locate search input using CSS attribute selector for input[type='search']
    search_input = wait.until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='search']"))
    )

    # Verify the search input is displayed
    assert search_input.is_displayed(), "Search input field is not visible"

    # Enter text into search input
    search_query = 'Selenium testing'
    search_input.clear()
    search_input.send_keys(search_query)

    # Submit the search by pressing Enter
    search_input.send_keys(Keys.ENTER)

    # Wait for URL to contain the search query
    wait.until(EC.url_contains(search_query.replace(' ', '+')))

    # Verify URL contains the search query
    current_url = driver.current_url
    assert search_query.replace(' ', '+') in current_url, f"URL does not contain search query. URL: {current_url}"

The script starts by opening the browser and navigating to the homepage.

It uses an explicit wait to find the search input field using a CSS attribute selector input[type='search']. This ensures the element is present before interacting.

We assert the input is visible to confirm it can be used.

Then, the script clears any existing text and types the search query 'Selenium testing'.

Pressing Enter submits the search form.

We wait until the URL contains the search query (spaces replaced by '+') to confirm the search results page loaded.

Finally, an assertion checks the URL contains the query string, verifying the search worked.

This approach uses best practices like explicit waits, clear selectors, and meaningful assertions.

Common Mistakes - 4 Pitfalls
{'mistake': 'Using hardcoded sleep instead of explicit waits', 'why_bad': 'Hardcoded sleeps slow tests and can cause flaky failures if the page loads slower or faster than expected.', 'correct_approach': "Use Selenium's explicit waits like WebDriverWait with expected_conditions to wait for elements or URL changes."}
{'mistake': 'Using incorrect CSS selector syntax like missing quotes in attribute selector', 'why_bad': 'Incorrect CSS selectors cause element not found errors and test failures.', 'correct_approach': "Use correct CSS attribute selector syntax, e.g., input[type='search'] with quotes around attribute value."}
Not verifying element visibility before interacting
{'mistake': 'Hardcoding URLs or search queries without handling spaces or encoding', 'why_bad': 'URLs may not match expected format causing assertion failures.', 'correct_approach': "Replace spaces with '+' or use URL encoding when checking URL contents."}
Bonus Challenge

Now add data-driven testing with 3 different search queries

Show Hint

Practice

(1/5)
1. What does the CSS selector input[type='text'] select in Selenium?
easy
A. All input elements regardless of type
B. All elements with any attribute containing 'text'
C. All elements with class 'text'
D. All input elements with type attribute exactly equal to 'text'

Solution

  1. Step 1: Understand the attribute selector syntax

    The selector input[type='text'] targets input tags with an attribute type exactly equal to 'text'.
  2. Step 2: Match the selector meaning to options

    All input elements with type attribute exactly equal to 'text' correctly describes this exact match. Other options describe different or incorrect matches.
  3. Final Answer:

    All input elements with type attribute exactly equal to 'text' -> Option D
  4. Quick Check:

    Exact attribute match = C [OK]
Hint: Exact match uses [attr='value'] syntax [OK]
Common Mistakes:
  • Confusing exact match with partial match
  • Selecting wrong tag type
  • Mixing class selectors with attribute selectors
2. Which of the following is the correct CSS selector to find elements with an attribute data-id that starts with 'user'?
easy
A. [data-id^='user']
B. [data-id*='user']
C. [data-id$='user']
D. [data-id='user']

Solution

  1. Step 1: Recall CSS attribute selectors for matching start of value

    The caret symbol ^= means 'starts with' in CSS attribute selectors.
  2. Step 2: Match the selector to the question

    [data-id^='user'] uses [data-id^='user'], which selects elements whose data-id attribute starts with 'user'.
  3. Final Answer:

    [data-id^='user'] -> Option A
  4. Quick Check:

    Starts with selector = B [OK]
Hint: Use ^= for 'starts with' attribute matching [OK]
Common Mistakes:
  • Using *= instead of ^= for starts with
  • Using $= which means ends with
  • Using exact match = instead of partial
3. What will the following Selenium Python code print if the page has three <input> elements with name attributes: 'user1', 'user2', and 'admin'?
elements = driver.find_elements(By.CSS_SELECTOR, "input[name*='user']")
print(len(elements))
medium
A. 2
B. 3
C. 1
D. 0

Solution

  1. Step 1: Understand the CSS selector input[name*='user']

    This selector finds input elements whose name attribute contains the substring 'user'.
  2. Step 2: Count matching elements

    Given names 'user1', 'user2', and 'admin', only 'user1' and 'user2' contain 'user'. So, 2 elements match.
  3. Final Answer:

    2 -> Option A
  4. Quick Check:

    Substring match count = 2 [OK]
Hint: Use *= to find attributes containing substring [OK]
Common Mistakes:
  • Counting all inputs instead of filtered ones
  • Confusing starts with (^) and contains (*) selectors
  • Assuming exact match instead of partial
4. You wrote this Selenium code but it throws an error:
element = driver.find_element(By.CSS_SELECTOR, "button[class^='submit']'")
What is the error and how to fix it?
medium
A. Wrong attribute selector; use *= instead of ^=
B. Extra single quote at the end; remove it to fix
C. Missing tag name before attribute selector
D. CSS selector cannot use ^ for attribute matching

Solution

  1. Step 1: Inspect the CSS selector string syntax

    The selector ends with an extra single quote after the closing double quote: "button[class^='submit']'". This causes a syntax error.
  2. Step 2: Correct the string by removing the extra quote

    Removing the extra single quote at the end fixes the syntax: "button[class^='submit']".
  3. Final Answer:

    Extra single quote at the end; remove it to fix -> Option B
  4. Quick Check:

    Check quotes balance = A [OK]
Hint: Check for balanced quotes in selectors [OK]
Common Mistakes:
  • Ignoring syntax errors caused by quotes
  • Changing correct attribute selectors unnecessarily
  • Assuming CSS does not support ^= selector
5. You want to select all <a> tags whose href attribute ends with '.pdf' or '.docx' using a single CSS selector in Selenium. Which selector is correct?
hard
A. a[href*='.pdf' or '.docx']
B. a[href$='.pdf' || href$='.docx']
C. a[href$='.pdf'], a[href$='.docx']
D. a[href$='.pdf'][href$='.docx']

Solution

  1. Step 1: Understand CSS selector for multiple attribute matches

    To select elements matching either condition, use a comma to separate selectors: a[href$='.pdf'], a[href$='.docx'].
  2. Step 2: Analyze other options for correctness

    a[href$='.pdf' || href$='.docx'] uses invalid syntax with || inside attribute selector. a[href$='.pdf'][href$='.docx'] requires both endings simultaneously, impossible. a[href*='.pdf' or '.docx'] uses invalid syntax with 'or'.
  3. Final Answer:

    a[href$='.pdf'], a[href$='.docx'] -> Option C
  4. Quick Check:

    Use comma to combine selectors = D [OK]
Hint: Combine selectors with comma for OR conditions [OK]
Common Mistakes:
  • Using logical operators inside attribute selectors
  • Trying to combine multiple attribute endings in one selector without comma
  • Assuming multiple attribute selectors mean OR instead of AND
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard