How to get the first paragraph in Selenium Python?

Selenium Python – Get first paragraph

In this tutorial, you will learn how to get the first paragraph in the document using Selenium in Python.

To get the first paragraph element in the document in Selenium Python, call find_element() method of the WebDriver object and pass the arguments: By.TAGNAME for by parameter and "p" for the value parameter.

Even if there are more than one paragraph elements in the document, find_element() returns only one element and that too the first one.

The following code snippet returns all the hidden paragraphs in the page.

driver.find_element(By.TAG_NAME, "p")

Examples

1. Get the first paragraph in the document

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

<html>
  <body>
    <h2>Hello User!</h2>
    <p>This is a paragraph.</p>
    <p>This is second paragraph.</p>
    <p>This is third paragraph.</p>
  </body>
</html>
Copy

In the following program, we initialize a webdriver, navigate to a specific URL (index.html), get the first paragraph element, and print the paragraph text to the standard output.

Python Program

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-6.html')

# Get the first paragraph element
first_paragraph = driver.find_element(By.TAG_NAME, "p")
print(first_paragraph.text)

# Close the driver
driver.quit()
Copy

Output

Selenium Python Example - Get first paragraph

Summary

In this Python Selenium tutorial, we have given instructions on how to get the first paragraph element in the document using find_element() method of WebDriver class, with example programs.

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 navigate back to the previous page in Selenium Python?

Not answered

Q3. Which of the following is not a commonly used assertion method 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 clear the text from an input field in Selenium Python?

Not answered
Code copied to clipboard successfully 👍