Selenium and Python to find elements and text?


We can find elements and its text with Selenium webdriver. First of all we have to identify the element with the help of any of the locators like id, classname, css and so on. Then to obtain the text we have to take the help of the text method.

Syntax

s = driver.find_element_by_css_selector("h4").text

Here driver is the webdriver object. The method find_element_by_css_selector is used to identify the element with css locator type and the locator value is passed as an argument to the method. Finally the text method is used to obtain the text content of the element.

Let us look at the html of an element having a text content. The output shall be You are browsing the best resource for Online Education.

Example

Code Implementation.

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe"
# implicit wait applied
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
# to identify element and obtain text
s = driver.find_element_by_css_selector("h4").text
print("The text is: " + s)

Output

Updated on: 26-Oct-2020

579 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements