+91 88606 33966            edu_sales@siriam.in                   Job Opening : On-site Functional Trainer/Instructor | Supply Chain Management (SCM)
Locating Strategies in Selenium : Locating by Id

Locators in Selenium are essential tools that help automate the tests to identify and interact with elements on a web page within the Document Object Model (DOM). It acts as a unique identifier for web elements, allowing testers to perform various actions such as clicking buttons, entering text, or validating the presence of elements.

Selenium provides different locator such as ID, Name, TagName, ClassName, XPath, CSS Selector, LinkText, and PartialLinkText. Each of the Locator type is suited to different scenarios based on the structure and attributes of the web page.

In the below activity, you will learn how to practically try this

So here we have taken the “siriam.in” website and I want to locate the search bar by the id.

1. Import Required Libraries:

webdriver: This module controls the browser (in this case, Chrome).

NoSuchElementException: Used to handle exceptions when an element cannot be found on the page.

By: Provides various locator strategies such as By.ID.

2. Initialize the WebDriver and set the Target url

Create a new instance of the Chrome browser. Make sure you have the ChromeDriver installed and set in your system’s PATH.

driver.get(url): Navigates to the specified URL.

3. Locating the Element by ID and handling the exception

find_element(By.ID, "masteriyo-course-search-field-0"): Attempts to find an element with the ID "masteriyo-course-search-field-0" on the loaded webpage.This line is placed inside a try block to catch potential exceptions if the element is not found.

If the element with the specified ID is not found, a NoSuchElementException is raised. The script prints "Not Found" to indicate the element couldn’t be located. If no exception is raised (i.e., the element is found), "Found" is printed to confirm successful element detection.

Now let’s see this in action.

Below is the Python program to implement Locating by ID:

# Python program to implement Locating by ID
from selenium import webdriver
from selenium.common import NoSuchElementException
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

# Replace this with your actual url
url = "https://siriam.in/"
driver.get(url)

# Replace ID_NAME with the Id of your element
try:
    # Replace this with the id of the element
    element = driver.find_element(By.ID, "masteriyo-course-search-field-0")
except NoSuchElementException:
    print("Not Found")
else:
    print("Found")

With this, you are done with the first locating web element strategies method.

Locating Strategies in Selenium : Locating by Id

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top