0
0
Selenium Pythontesting~5 mins

Finding multiple elements in Selenium Python

Choose your learning style9 modes available
Introduction

Finding multiple elements helps you check many parts of a webpage at once. It is useful when you want to test lists, tables, or groups of similar items.

You want to check all buttons on a page to see if they are clickable.
You need to verify all links in a menu are present and correct.
You want to count how many items appear in a search result.
You want to test if all images in a gallery load properly.
Syntax
Selenium Python
elements = driver.find_elements(By.LOCATOR_TYPE, "locator_value")

find_elements returns a list of matching elements, even if empty.

Use By to specify how to find elements, like by ID, class, or tag.

Examples
This finds all button elements on the page.
Selenium Python
buttons = driver.find_elements(By.TAG_NAME, "button")
This finds all elements with the class 'nav-link'.
Selenium Python
links = driver.find_elements(By.CLASS_NAME, "nav-link")
This finds all elements matching the CSS selector '.list-item'.
Selenium Python
items = driver.find_elements(By.CSS_SELECTOR, ".list-item")
Sample Program

This script opens a small HTML page with a list of fruits. It finds all list items with the class 'fruit' and prints their names one by one.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

# Setup driver with headless option (make sure chromedriver is in PATH)
options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)

# Open a simple test page
html = '''
<html>
  <body>
    <ul>
      <li class="fruit">Apple</li>
      <li class="fruit">Banana</li>
      <li class="fruit">Cherry</li>
    </ul>
  </body>
</html>
'''

# Load the HTML content
driver.get("data:text/html;charset=utf-8," + html)

# Find all list items with class 'fruit'
fruits = driver.find_elements(By.CLASS_NAME, "fruit")

# Print the text of each fruit
for fruit in fruits:
    print(fruit.text)

# Close the driver
driver.quit()
OutputSuccess
Important Notes

If no elements match, find_elements returns an empty list, not an error.

Always close the driver after tests to free resources.

Summary

Use find_elements to get many elements at once.

The result is a list you can loop through.

It helps test groups of similar page parts easily.