0
0
Selenium Pythontesting~5 mins

Getting element text in Selenium Python

Choose your learning style9 modes available
Introduction

We get the text from a web element to check what the user sees on the page.

To verify a button label matches what is expected.
To check if a message or alert text appears correctly after an action.
To confirm that a heading or paragraph contains the right content.
To read the text inside a list or table cell for validation.
To capture dynamic text that changes after user interaction.
Syntax
Selenium Python
element_text = driver.find_element(By.LOCATOR_TYPE, "locator_value").text

Use By with the right locator type like ID, CSS_SELECTOR, or XPATH.

The .text property gets the visible text inside the element.

Examples
Get text from a button with ID 'submit-btn'.
Selenium Python
button_text = driver.find_element(By.ID, "submit-btn").text
Get text from a header using a CSS selector.
Selenium Python
header_text = driver.find_element(By.CSS_SELECTOR, "h1.main-title").text
Get text from an alert message using XPath.
Selenium Python
alert_text = driver.find_element(By.XPATH, "//div[@class='alert-message']").text
Sample Program

This script opens a webpage, finds the main heading <h1>, gets its visible text, prints it, then closes the browser.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By

# Setup driver (make sure chromedriver is in PATH)
driver = webdriver.Chrome()

# Open example page
url = "https://example.com"
driver.get(url)

# Find the heading and get its text
heading = driver.find_element(By.TAG_NAME, "h1")
heading_text = heading.text

print(f"Heading text is: '{heading_text}'")

# Close the browser
driver.quit()
OutputSuccess
Important Notes

The .text property only returns visible text, not hidden or script content.

If the element has child elements, .text returns combined visible text inside.

Always wait for the element to be present and visible before getting text to avoid errors.

Summary

Use .text to get visible text from a web element.

Locate the element first with a proper locator strategy.

Check the text to verify what the user sees on the page.