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.
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");
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')
Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.