Locate and verify element using CSS selector
Preconditions (2)
✅ Expected Result: The element with id 'submit-button' and class 'btn-primary' is found and visible on the page.
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Initialize the WebDriver (e.g., Chrome) driver = webdriver.Chrome() try: # Open the target web page driver.get('https://example.com') # Replace with actual URL # Wait up to 10 seconds for the element to be visible wait = WebDriverWait(driver, 10) element = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '#submit-button.btn-primary'))) # Assert the element is displayed assert element.is_displayed(), "Element is not visible on the page" finally: # Close the browser driver.quit()
This script starts by importing necessary Selenium modules.
It opens the browser and navigates to the target page.
Using WebDriverWait with visibility_of_element_located ensures the script waits until the element matching the CSS selector #submit-button.btn-primary is visible.
The assertion element.is_displayed() confirms the element is visible on the page.
Finally, the browser is closed to clean up.
This approach avoids using fixed waits and uses best practices for locating elements by CSS selector.
Now add data-driven testing with 3 different CSS selectors to verify multiple elements.
driver.find_element(By.CSS_SELECTOR, "selector").element = driver.find_element(By.CSS_SELECTOR, "div#main > ul.items > li.active")
element = driver.find_element(By.CSS_SELECTOR, "#content .item[active]")
<input> elements inside a form with id "loginForm" that have both classes "input-field" and "required". Which CSS selector should you use with Selenium Python's find_elements method?.input-field.required.form#loginForm to select the form by id, then space to select descendants, then input.input-field.required for inputs with both classes.Pass the test and this pattern moves unknown