How can I use the selenium’s get Text method for verifying a specific element?

35    Asked by debbieJha in QA Testing , Asked on Apr 12, 2024

 I am currently working on a project that is related to automating the testing of a web-based application by using selenium. However, when I was going through with the workflow I needed to verify whether a specific element on a webpage displayed the correct text or not. How can I use the selenium’s get Text method for this particular Objective? 

Answered by Donna Chapman

In the context of selenium, here is how you can use the selenium’s get Text method in Java programming language for the purpose of retrieving the text from a Web page element and then validate it against the expected text:-

Import org.openqa.selenium.By;
Import org.openqa.selenium.WebDriver;
Import org.openqa.selenium.WebElement;
Import org.openqa.selenium.chrome.ChromeDriver;
Public class TextValidation {
    Public static void main(String[] args) {
        // Set the path to chromedriver.exe
        System.setProperty(“webdriver.chrome.driver”, “path_to_chromedriver.exe”);
        // Initialize ChromeDriver
        WebDriver driver = new ChromeDriver();
        // Open the webpage
        Driver.get(https://www.example.com);
        // Find the element by its ID, class name, XPath, or other locators
        WebElement element = driver.findElement(By.id(“element_id”));
        // Use getText() method to retrieve the text from the element
        String actualText = element.getText();
        // Define the expected text
        String expectedText = “Expected Text”;
        // Validate the actual text against the expected text
        If (actualText.equals(expectedText)) {
            System.out.println(“Text validation successful. Actual text matches expected text.”);
        } else {
            System.out.println(“Text validation failed. Actual text does not match expected text.”);
        }
        // Close the browser
        Driver.quit();
    }
}

Here is the same coding given in the form of Python programming language:-

From selenium import webdriver
# Set the path to chromedriver.exe or geckodriver.exe based on the browser you’re using
Driver = webdriver.Chrome(executable_path=”path_to_chromedriver.exe”)
# Open the webpage
Driver.get(https://www.example.com)
# Find the element by its ID, class name, XPath, or other locators
Element = driver.find_element_by_id(“element_id”)
# Use getText() method to retrieve the text from the element
Actual_text = element.text
# Define the expected text
Expected_text = “Expected Text”
# Validate the actual text against the expected text
If actual_text == expected_text:
    Print(“Text validation successful. Actual text matches expected text.”)
Else:
    Print(“Text validation failed. Actual text does not match expected text.”)
# Close the browser
Driver.quit()


Your Answer

Interviews

Parent Categories