Contents
Selenium Python – Get div with specific id
In this tutorial, you will learn how to get a div element with a specific id attribute in the document using Selenium in Python.
To get a div element with specific id attribute value in Selenium Python, call find_element() method of the element object and pass the arguments: "By.ID" for by parameter and your required id value for the value parameter.
The following code snippet returns the div element whose id="mydiv2" in the page.
driver.find_element(By.ID, "mydiv2")
The find_element() method returns a WebElement object, if the object is present, else it throws NoSuchElementException. Therefore it is recommended to wrap the find_element() code in try-except.
Examples
1. Get the div element whose id=”mydiv2″
In the following examples, we shall consider loading the HTML file at path https://pythonexamples.org/tmp/selenium/index-4.html . The contents of this HTML file is given below.
<html>
<body>
<div id="mydiv1">Apple</div>
<div id="mydiv2">Banana</div>
<div id="mydiv3">Cherry</div>
</body>
</html>
Copy In the following program, we initialize a webdriver, navigate to a specific URL, get the div element whose id="mydiv2", and print its text to standard output.
Python Program
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
# Setup chrome driver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
# Navigate to the url
driver.get('https://pythonexamples.org/tmp/selenium/index-4.html')
# Get the div element by ID
try:
div_element = driver.find_element(By.ID, "mydiv2")
print(div_element.text)
except NoSuchElementException:
print("The div element does not exist.")
# Close the driver
driver.quit()
CopyOutput
Summary
In this Python Selenium tutorial, we have given instructions on how to get the div element with a specific id using find_element() method of WebElement class, with example programs.