How to get text of paragraph in Selenium Python?

Get Paragraph Text in Selenium Python

To get text of a paragraph element in Selenium Python, you can read the text attribute of the paragraph WebElement.

For example, if my_para is the given paragraph WebElement, then the syntax to get the text of this paragraph is

my_para.text

The text property returns a string value representing the text in the paragraph element.

Examples

In this example, we shall consider loading the HTML file at URL https://pythonexamples.org/tmp/selenium/index-10.html . The contents of this HTML file is given below.

<html>
<head></head>
<body>
    <h2>Hello User!</h2>
    <p id="msg">This is my <strong>first</strong> paragraph. This is a sample text. Welcome!</p>
    <div id="mydiv">
      <div class="child">Child 1</div> <div class="child">Child 2</div>
    </div> 
</body>
</html>
Copy
Get Paragraph Text in Selenium Python

Now, we shall get the paragraph with id=”msg” and print the text of this paragraph to standard output.

Python Program (Selenium)

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By

# Setup chrome driver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))

# Navigate to the url
driver.get('https://pythonexamples.org/tmp/selenium/index-10.html')

# Find the paragraph element
my_para = driver.find_element(By.ID, 'msg')

# Get the paragraph text
para_text = my_para.text
print(para_text)

# Close the browser
driver.quit()

Output

This is my first paragraph. This is a sample text. Welcome!

Please observe the output. Even though there is a <strong> element inside the paragraph, that element is replaced with the visible text. So, the text property of a paragraph element returns just the text.

Summary

In this Python Selenium tutorial, we learned how to get the text of a paragraph element in a webpage, using WebElement.text property in Selenium.

Related Tutorials

Quiz on Selenium

Q1. Which of the following is not a popular web driver used in Selenium Python?

Not answered

Q2. What is the method used to interact with web elements in Selenium Python?

Not answered

Q3. Which of the following is not a method to wait for a web element to load in Selenium Python?

Not answered

Q4. Which of the following is not a commonly used web element locator in Selenium Python?

Not answered

Q5. What is the method used to select a value from a drop-down list in Selenium Python?

Not answered
Code copied to clipboard successfully 👍