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.

Related Tutorials

Quiz on Selenium

Q1. What is Selenium Python used for?

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. What is the method used to take a screenshot 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 👍