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.
driver_instance.find_element("tag name","provide your tag here")
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
.
Let's take a look at an example of this.
#import librariesfrom selenium import webdriverfrom selenium.webdriver.chrome.options import Options#provide chrome optionsoptions = Options()options.add_argument("--headless")options.add_argument("--no-sandbox")#get instance of web driverdriver = webdriver.Chrome(options=options)#provide website url heredriver.get("https://omayo.blogspot.com/")#locate element by tag nameprint(driver.find_element("tag name","h2").text)
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