Get Text Selenium Method

In Selenium with Python, the text method retrieves the visible text from a web element. This is useful when you need to get the content of an element like a <div>, <span>, <p>, or any other HTML tag that contains text.

Example:

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

# Initialize the WebDriver (this example uses Chrome)
driver = webdriver.Chrome()

# Open a webpage
driver.get("https://sqatools.in/dummy-booking-website/")

# Locate the element containing the header of website
element = driver.find_element(By.TAG_NAME, "h1")

# Get the heading text from the element
text_content = element.text

# Print the text content
print(text_content)  # Dummy Ticket Booking Website

# Close the browser
driver.quit()

Steps:

  1. Initialize the WebDriver: Start the WebDriver for the browser you want to use.
  2. Navigate to the webpage: Use driver.get() to open the page where the target element is located.
  3. Find the element: Use one of the find_element methods (e.g., find_element(By.ID, By.XPATH, By.CLASS_NAME)) to locate the element.
  4. Retrieve the text: Use the text method on the element to get its visible text.
  5. Display or use the text: The text attribute returns the text as a string, which you can print or use in your logic.

Example using XPath:

element =driver.find_element(By.XPATH,"//div[@class='example-class']")
text_content = element.text
print(text_content)

Important Notes:

  • The text method only retrieves visible text: If the text is hidden via CSS (display: none;, visibility: hidden;, etc.), Selenium will not retrieve it.
  • Whitespace handling: The text method preserves the text formatting as it appears in the browser, so you may get extra spaces or line breaks.