Get first paragraph in Selenium
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 /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>
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('/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()
Output
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.