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.
- Selenium Features
- Selenium Installation
- Selenium Locators
- XPath Fundamentals
- CSS Selectors Methods
- Different Browsers Execution
- find_element & find_elements
- Check Enabled Status
- Check Displayed Status
- Check Selected Status
- Selenium Waits
- Send_keys Method
- Click Method
- Get Text
- Get Attribute Value
- Get Current URL
- Forward, Back, Refresh
- Take Screenshot
- Handle Browser Tabs
- Handle iframe
- Mouse Hover
- Context-Click
- Drag & Drop
- Handle Alerts
- Handle Dropdown
- Execute Javascript
- Scroll To element
- Headless Mode Execution
- Chrome Options
- Keyboard Action
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:
- Initialize the WebDriver: Start the WebDriver for the browser you want to use.
- Navigate to the webpage: Use driver.get() to open the page where the target element is located.
- 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.
- Retrieve the text: Use the text method on the element to get its visible text.
- 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.