In Selenium, two commonly used methods to locate elements on a web page are find_element and find_elements . They allow you to interact with HTML elements like buttons, links, text fields, etc. Let’s break them down
- Selenium Features
- Selenium Installation
- Selenium Locators
- XPath Fundamentals
- CSS Selectors Methods
- Different Browsers Execution
- find_element & find_elements
- Check Enabled Status
- Check Displayed Status
- Check Selected Status
- Selenium Waits
- Send_keys Method
- Click Method
- Get Text
- Get Attribute Value
- Get Current URL
- Forward, Back, Refresh
- Take Screenshot
- Handle Browser Tabs
- Handle iframe
- Mouse Hover
- Context-Click
- Drag & Drop
- Handle Alerts
- Handle Dropdown
- Execute Javascript
- Scroll To element
- Headless Mode Execution
- Chrome Options
- Keyboard Action
find_element Method
The find_element method is used to locate a single web element on the page. It returns the first matching element it finds. If it doesn’t find the element, it will raise a NoSuchElementException
.
Syntax:
element = driver.find_element(by, value)
- By : Locator strategy (e.g., By.ID, By.XPATH, By.Name, etc.).
- value: The value that matches the element you want to find (e.g., the element’s ID, name, class, or other attributes).
Example:
If you want to find an element by its ID:
element = driver.find_element(By.ID, 'username')
element.send_keys('my_username')
Here, Selenium will locate the element with the ID username and send a text to it.
Common Locator Strategies for find_element
:
- By.ID : Finds an element by its ID attribute.
- By.NAME: Finds an element by its name attribute.
- By.CLASS_NAME: Locates elements by the class name.
- By
.
XPATH: Locates elements using an XPath expression. - By.CSS_SELECTOR: Finds elements using a CSS selector.
- By.TAG_NAME: Locates elements by their tag name (e.g.,
h1
,input
).
find_elements Method
The find_elements method is used to locate multiple elements on a web page. It returns a list of all matching elements. If no elements are found, it returns an empty list (instead of raising an exception).
Syntax:
elements = driver.find_elements(by, value)
- Similar to find_element, but it returns a list of elements.
Example:
To find all elements with a specific class name:
elements = driver.find_elements(By.CLASS_NAME, 'product')
for element in elements:
print(element.text)
In this case, all elements with the class name product
will be located, and their text content will be printed.
Key Differences Between find_element and find_elements:
find_element | find_elements |
---|---|
Returns one element (the first match) | Returns a list of matching elements |
Raises NoSuchElementException if no element is found | Returns an empty list if no elements are found |
Best for situations where only one element is expected | It is ideal when you want to find multiple elements (e.g., list items, products) |