How to get div with specific id in Selenium Python?

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.


1. Get the div element whose id=”mydiv2″

In this example, we shall consider loading the following HTML file via the driver object.


    <div id="mydiv1">Apple</div>
    <div id="mydiv2">Banana</div>
    <div id="mydiv3">Cherry</div>

In the following program, we initialize a webdriver, navigate to a specific URL (index.html), get the div element whose id="mydiv2", and print its text to standard output.

Python Program

from selenium import webdriver
from import ChromeDriverManager
from import Service as ChromeService
from import By
from selenium.common.exceptions import NoSuchElementException

# Setup chrome driver
service = ChromeService(executable_path=ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)

# Navigate to the url

# Get the div element by ID
    div_element = driver.find_element(By.ID, "mydiv2")
except NoSuchElementException:
    print("The div element does not exist.")

# Close the driver


Selenium Python Example - Get div with specific id


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.

Quiz on Selenium

Q1. What is Selenium Python used for?

Not answered

Q2. What is a web driver in Selenium Python?

Not answered

Q3. What is the method used to interact with web elements in Selenium Python?

Not answered

Q4. What is the method used to navigate back to the previous page in Selenium Python?

Not answered

Q5. What is the method used to select a value from a drop-down list in Selenium Python?

Not answered