Open In App

How to select the text of a span on click in Selenium?

Last Updated : 28 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Selenium, to interact with a span element and get its text, you first need to identify the element. Then, perform a click action on it. After clicking, you can extract the text content of the span. This process helps automate the testing of web pages by simulating user interactions and retrieving data.

Setup

We need to install Selenium on our system and a WebDriver, like ChromeDriver, set up properly. Selenium is needed to automate web interactions, and the WebDriver acts as a bridge between your code and the browser, allowing you to control it for testing purposes.

pip install selenium

Verify Installation:

import selenium
print(selenium.__version__)

Example:

Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

# Initialize the WebDriver
driver = webdriver.Chrome()  # or any other WebDriver

# Open the target web page
driver.get('http://localhost:3000/')  # replace with your URL

# Locate the span element
span_element = driver.find_element(By.XPATH, '//span[@id="mySpan"]')  # adjust XPath or selector

# Click the span element
span_element.click()

# Get the text of the span element
span_text = span_element.text

# Print the text
print("Span Text:", span_text)

# Close the WebDriver
driver.quit()
HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Selenium Test</title>
</head>
<body>
    <h1>Welcome to Selenium Testing</h1>
    <p>This is a sample paragraph with a <span id="mySpan">Click me!</span> element.</p>
</body>
</html>

Output:

Span Text: Click me!

Conclusion

Selenium WebDriver lets you interact with web elements and retrieve their text content for testing or data extraction. By automating these tasks, you can efficiently validate web applications and gather information from web pages, making it a valuable tool for ensuring functionality and accuracy in your projects.


Next Article
Article Tags :

Similar Reads