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 this example, we shall consider loading the following HTML file via the driver object.

index.html

<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>

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 webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By

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

# Navigate to the url
driver.get('http://127.0.0.1:5500/index.html')

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

# Close the driver
driver.quit()

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. What is a web driver in Selenium Python?

Not answered

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

Not answered

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

Not answered

Q4. What is the method used to navigate back to the previous page in Selenium Python?

Not answered

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

Not answered