Locating elements by TagName in selenium python

Selenium is an open-source web-based automation tool. To interact with DOM elements, first, we need to locate elements and then perform automation or tests on elements. In this answer, we’ll learn how to locate elements in DOM by tag name in selenium python.

We will use the find_element method to locate the element by tag name.

Syntax

driver_instance.find_element("tag name","provide your tag here")

Parameters & return value

We will provide the tag name as the first parameter and provide the tag in the second parameter to locate elements by tag name.

This method returns the first element that matches the given tag name.

Example

Let's take a look at an example of this.

#import libraries
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#provide chrome options
options = Options()
options.add_argument("--headless")
options.add_argument("--no-sandbox")
#get instance of web driver
driver = webdriver.Chrome(options=options)
#provide website url here
driver.get("https://omayo.blogspot.com/")
#locate element by tag name
print(driver.find_element("tag name","h2").text)

Explanation

  • Line 6-8: We create an instance of the Options() class to specify how chrome should run. Here we run chrome as headless, meaning no browser will be physically opened.

  • Line 12: We get the instance of the webdriver by passing options as a parameter to it and assign it to the driver variable.

  • Line 15: We provide the URL to the driver.get() method to open it in a headless web browser.

  • Line 18: We locate the element by tag name as h2 using the find_element() method and display the text present in it.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved