0
0
Selenium Pythontesting~15 mins

Finding multiple elements in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Verify multiple product items are displayed on the products page
Preconditions (2)
Step 1: Open the products page URL
Step 2: Locate all product item elements by their common CSS class 'product-item'
Step 3: Count the number of product item elements found
✅ Expected Result: At least 3 product item elements are found and visible on the page
Automation Requirements - Selenium with Python
Assertions Needed:
Assert that the number of product items found is greater than or equal to 3
Assert that each product item element is displayed (visible)
Best Practices:
Use explicit waits to wait for product items to be present
Use By.CLASS_NAME locator for product items
Avoid hardcoded sleeps
Use Page Object Model pattern for maintainability
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

class ProductsPage:
    def __init__(self, driver):
        self.driver = driver
        self.product_items_locator = (By.CLASS_NAME, 'product-item')

    def wait_for_products(self):
        WebDriverWait(self.driver, 10).until(
            EC.presence_of_all_elements_located(self.product_items_locator)
        )

    def get_product_items(self):
        return self.driver.find_elements(*self.product_items_locator)


def test_multiple_product_items_displayed():
    driver = webdriver.Chrome()
    try:
        driver.get('https://example.com/products')
        products_page = ProductsPage(driver)
        products_page.wait_for_products()
        items = products_page.get_product_items()

        assert len(items) >= 3, f'Expected at least 3 product items, found {len(items)}'

        for item in items:
            assert item.is_displayed(), 'Product item is not visible'
    finally:
        driver.quit()

The ProductsPage class uses the Page Object Model to keep locators and actions organized.

We use WebDriverWait with presence_of_all_elements_located to wait until product items appear on the page, avoiding fixed delays.

The test opens the products page URL, waits for product items, then finds all elements with the class product-item.

We assert that there are at least 3 such elements, matching the manual test case expectation.

We also check each product item is visible using is_displayed().

Finally, the browser is closed in a finally block to ensure cleanup.

Common Mistakes - 3 Pitfalls
Using time.sleep() instead of explicit waits
Using find_element instead of find_elements to get multiple elements
Using brittle XPath or CSS selectors that depend on exact element hierarchy
Bonus Challenge

Now add data-driven testing with 3 different product pages URLs to verify multiple product items on each page.

Show Hint