0
0
Selenium Pythontesting~15 mins

Find element by CSS selector in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Locate and verify element using CSS selector
Preconditions (2)
Step 1: Open the target web page in the browser.
Step 2: Locate the element using the CSS selector '#submit-button.btn-primary'.
Step 3: Verify that the element is displayed on the page.
✅ Expected Result: The element with id 'submit-button' and class 'btn-primary' is found and visible on the page.
Automation Requirements - Selenium with Python
Assertions Needed:
Assert the element is found using the CSS selector.
Assert the element is visible (displayed) on the page.
Best Practices:
Use explicit waits to wait for the element to be present and visible.
Use By.CSS_SELECTOR locator strategy.
Avoid hardcoded sleeps.
Handle exceptions if element is not found.
Automated Solution
Selenium Python
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.

Common Mistakes - 4 Pitfalls
Using driver.find_element without waits
{'mistake': 'Using incorrect CSS selector syntax', 'why_bad': "The element won't be found if the selector is wrong.", 'correct_approach': "Use valid CSS selector syntax, e.g., '#id.class' for element with id and class."}
Using hardcoded sleep instead of waits
Not handling exceptions when element is missing
Bonus Challenge

Now add data-driven testing with 3 different CSS selectors to verify multiple elements.

Show Hint