Screenshot of a particular element with Python Selenium in Linux



We can capture a screenshot of a particular element with Selenium webdriver in Python. To achieve this task, first we have to identify the element which we want to identify with the help of any locators like id, xpath, css, name, class name, tagname, link text or partial link text.

After the element has been identified, we can capture its screenshot with the help of the screenshot method. We have to pass the file name where the screenshot shall be stored (along with extension) as a parameter to this method

Syntax

m=driver.find_element_by_tag_name("h4")
m.screenshot("logo.png")

Let us capture the screenshot of the highlighted text below −

Example

from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://www.tutorialspoint.com/index.htm")
#identify element
m = driver.find_element_by_tag_name("h4")
#capture screenshot and save it in .png extension
m.screenshot("screenshot_text.png")
#browser quit
driver.quit()

Output


Advertisements