Screenshot in selenium python

Test cases may fail while executing the test suite in selenium automation. When manual tester face any discrepancy in the verification i.e. when there is a difference in actual and expected values , manual testers tend to take screenshot as proof for failure.

    Failures may occur because of below reasons:
  • Actual and Expected values are not matching
  • When there is no element
  • When page takes more time to load
  • When an unexpected alert comes in to focus
  • When there is Assertion issues

We can take screenshot of an webpage in selenium python using save_screenshot() method, save_screenshot() will take the complete page as screenshot.


from selenium import webdriver
driver = webdriver.Firefox(executable_path='[Browser Driver Path]');
driver.get('https://www.google.co.in');
driver.save_screenshot("screenshot.png");		

Take element Screenshot

Selenium Python does not provide any methods to take screenshot of an element, so we will be using the PIL library to crop the element out of the webpage.


from selenium import webdriver
from PIL import Image
driver = webdriver.Firefox(executable_path='[Browser Driver Path]');
driver.get('https://www.google.co.in');
element = driver.find_element_by_name("q");
location = element.location;
size = element.size;
driver.save_screenshot("pageImage.png");
x = location['x'];
y = location['y'];
width = location['x']+size['width'];
height = location['y']+size['height'];
im = Image.open('pageImage.png')
im = im.crop((int(x), int(y), int(width), int(height)))
im.save('element_image.png')		

About Author

Article is written by Pavan (a) KarthiQ. Well, I am serving notice period in an MNC, Bangalore. I thought to enrich every person knowledge a little, I always have a feeling, when we teach something, we will learn more than what you know. Knowledge is the only thing that doubles when you spend it.

I have also created the reporter for Protractor Jasmine. Use for your projects without any hesitation

You can also share knowledge by Adding a topic here


Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions