Python Selenium - Get Paragraph Text


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 /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>
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('/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.