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.
driver.find_element()driver.find_elements()
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.
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.from selenium import webdriverfrom selenium.webdriver.common.by import Byimport time#specify where your chrome driver present in your pcPATH=r"C:\Users\educative\Documents\chromedriver\chromedriver.exe"#get instance of web driverdriver = webdriver.Chrome(PATH)#provide website url heredriver.get("https://www.educative.io/answers")#sleep for 2 secondstime.sleep(2)#usage of find elementprint(driver.find_element(By.xpath('//*[@class="list-masonry-grid_column"]/a/div/h2')).text)#usage of find_elementsfor ele in driver.find_elements(By.xpath('//*[@class="list-masonry-grid_column"]/a/div/h2')):print(ele.text)
title
using the find_element()
method.title
using the find_elements()
method. We loop through the returned list of elements and print its text.Free Resources