How can I use the selenium in Python for retrieving and verifying the text of the element dynamically?

311    Asked by Bhaanumatishukla in QA Testing , Asked on Feb 21, 2024

I have been asked for a particular scenario where I have to work on automating a web-based application in which I need to verify the text of an element, such as a heading or a paragraph. Explain to me how can I use the selenium in Python programming language to retrieve and even verify the text of that element dynamically. 

Answered by Delbert Rauch

 In the context of selenium, you can retrieve and even verify the text of an element in a web-based application by using selenium in Python programming language by using these steps which are given below:-

First, you would need to use a web driver to open the webpage.

Then you would need to locate the element whose text you want to be retrieved by using locators such as Xpath, CSS, etc.

You can use the “text” attribute for extracting the text content of the element.

Try to compare the retrieved text with the expected text for verification.

Here is how you can implement it in Python programming language:-

From selenium import webdriver

# Initialize the WebDriver (assuming Chrome in this example)
Driver = webdriver.Chrome()
# Open the webpage
Driver.get(https://example.com)
# Locate the element whose text you want to retrieve (e.g., a heading)
Heading_element = driver.find_element_by_xpath(“//h1”)
# Retrieve the text of the element
Element_text = heading_element.text
# Print the retrieved text
Print(“Text of the heading element:”, element_text)
# Compare the retrieved text with the expected text to verify it
Expected_text = “Welcome to Example.com”
If element_text == expected_text:
    Print(“Text verification passed!”)
Else:
    Print(“Text verification failed. Expected:”, expected_text, “Actual:”, element_text)
# Close the WebDriver
Driver.quit()


Your Answer

Interviews

Parent Categories