CSS attribute selectors in Selenium Python - Build an Automation Script
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.
Now add data-driven testing with 3 different search queries