How to get the screenshot of a particular section of the page like the logo of a website in Selenium with python?

Selenium Web DriverAutomation TestingSoftware Testing

We can capture the screenshot of a particular section of the page like the logo of the website in Selenium. For doing so we need to import a PIL imaging library. It may or may not be a part of the standard libraries. However if it is unavailable, it can be installed with pip install Pillow command.

For capturing the screenshot, get_screenshot_as_png() method is available. This method gives a binary data which is present in the memory. Then the image can be modified and finally saved.

There is no built-in method to capture the logo of the web site separately. To achieve this we have to crop the image of the full page to the size of the image logo.



In the arguments, we have to provide the screenshot file name along with the extension of .png. If anything else is used as extension, a warning message will be thrown and the image cannot be viewed.

The screenshot gets saved in the same path of the program.

Finally we need to crop the image with the help of location and size methods in Webdriver.

Every element has a unique location measured by the (x, y) co-ordinates. The location method gives two values – x and y coordinates.

Every element has a dimension defined by its height and width. These values are obtained by size method, which gives two values - height and width.

Now for cropping the image.

# to get the axes
l = location['x'];
t = location['y'];
r = location['x']+size['width'];
b = location['y']+size['height'];
# to compute the cropped image dimension
cropImage ='screenshot_t.png')
cropImage = cropImage.crop(l, t, r, b))'cropImage.png')


Code Implementation for capturing a section of a page.

from selenium import webdriver
from PIL import Image
from io import BytesIO
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
#get method to launch the URL
#to refresh the browser
# identifying the logo to capture the screenshot
s= driver.find_element_by_xpath("//img[@class='top-logo']")
# to get the element location
location = s.location
# to get the dimension the element
size = s.size
#to save the screenshot of complete page
p = driver.get_screenshot_as_png("logo_tutorialspoint.png")
#to get the x axis
l = location['x']
#to get the y axis
t = location['y']
# to get the length the element
b = location['y']+size['height']
# to get the width the element
r = location['x']+size['width']
# to open the captured image with PIL
imgOpen =
# to crop the captured image to size of the logo
imgLogo = imgLogo.crop(l, t, r, b)
# to save the cropped image"logo_tutorialspoint.png")
#to close the browser
Updated on 29-Jul-2020 10:53:53