Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

What are find_element and find_elements in Selenium Python?

Gutha Vamsi Krishna

Overview

Selenium is an open-source web-based automation tool. In this answer, we'll learn how to use the find_element and find_elements commands in Selenium web driver using Python.

Syntax

driver.find_element()
driver.find_elements()

Parameters

Both commands take the type of attribute (class name, ID, XPath, and so on) as the first parameter and the value of that in the second parameter.

Return value

  • find_element() returns the first element that matches and returns NoSuchElementException if no match is found.
  • find_elements() returns a list of elements that match and returns an empty list if no match is found.

Example

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

#specify where your chrome driver present in your pc
PATH=r"C:\Users\educative\Documents\chromedriver\chromedriver.exe"

#get instance of web driver
driver = webdriver.Chrome(PATH)

#provide website url here
driver.get("https://www.educative.io/answers")

#sleep for 2 seconds
time.sleep(2)

#usage of find element
print(driver.find_element(By.xpath('//*[@class="list-masonry-grid_column"]/a/div/h2')).text)

#usage of find_elements
for ele in driver.find_elements(By.xpath('//*[@class="list-masonry-grid_column"]/a/div/h2')):
    print(ele.text)
The find element and find elements in Selenium Python

Explanation

  • Line 18: We get the first element that has a class name title using the find_element() method.
  • Lines 21–22: We get all the elements that have a class name title using the find_elements() method. We loop through the returned list of elements and print its text.

RELATED TAGS

python

CONTRIBUTOR

Gutha Vamsi Krishna
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring