How to take partial screenshot with Selenium WebDriver in python?

SeleniumAutomation TestingTesting ToolsPython

We can take a partial screenshot with Selenium webdriver. To capture the screenshot of a particular element we have to first identify the element with the help of the locators like id, name, classname and so on.

Then we have to apply the screenshot method on that webelement and pass the image name with extension as an argument to the method. A new file containing the screenshot of that webelement gets created in the project folder.

Syntax

l=driver.find_element_by_xpath("//img[@title='Tutorialspoint']")
l.screenshot("logo.png")

Let us obtain the screenshot of the logo of the webpage.

Example

Code Implementation

from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
driver.maximize_window()
driver.get("https://www.tutorialspoint.com/index.htm")
# identify element to capture the screenshot
l=driver.find_element_by_xpath("//img[@title='Tutorialspoint']")
# capture the screenshot with screenshot method
l.screenshot("logo.png")

Output

A new file name logo.png containing a screenshot of the element gets created in the project folder.

raja
Published on 26-Oct-2020 10:35:46
Advertisements