Selenium WebDriver provides two methods to find elements from a web page - find_element
and find_elements
. These methods are used to find elements on a webpage and interact with them, like clicking a button, entering text in a field, selecting from a dropdown, etc.
The find_element
and find_elements
methods are part of the WebDriver API and are available in all languages supported by Selenium, such as Python and JavaScript. Here are the differences between them:
find_element
: This method returns the first matching element on the web page. It throws aNoSuchElementException
if no matching elements are found on the page. This is primarily used when you know there's only one element that matches your criteria, or you only want to interact with the first matching element.find_elements
: This method returns a list of all matching elements on the web page. It returns an empty list if no elements match the search criterion. This is primarily used when you want to interact with multiple elements that match your criteria, like all items in a list, all options in a dropdown, etc.
Here's a Python example using both methods:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.example.com")
# using find_element
first_paragraph = driver.find_element_by_tag_name('p')
# using find_elements
all_paragraphs = driver.find_elements_by_tag_name('p')
And here's a JavaScript example:
const {Builder, By, Key, until} = require('selenium-webdriver');
let driver = new Builder()
.forBrowser('firefox')
.build();
driver.get('http://www.example.com');
// using findElement
let firstParagraph = driver.findElement(By.tagName('p'));
// using findElements
let allParagraphs = driver.findElements(By.tagName('p'));
In both examples, find_element_by_tag_name('p')
or findElement(By.tagName('p'))
will return the first paragraph element on the page, while find_elements_by_tag_name('p')
or findElements(By.tagName('p'))
will return all paragraph elements on the page.