How to take partial screenshot with Selenium WebDriver in python?

0
0

I have searched a lot for this but couldn’t find a solution. Here’s a similar question with a possible solution in java.

Is there a similar solution in Python?

  • You must to post comments
0
0

This question seems to have gone a long time without an answer, but having just worked on it I thought I would pass on some of the things I’ve learned

Note: Other than Selenium this example also requires the PIL Imaging library. Sometimes this is put in as one of the standard libraries and sometimes it’s not, but if you don’t have it you can get it here

from selenium import webdriver
from PIL import Image
fox
= webdriver.Firefox()
fox
.get('http://stackoverflow.com/')
# now that we have the preliminary stuff out of the way time to get that image :D
element
= fox.find_element_by_id('hlogo') # find part of the page you want image of
location
= element.location
size
= element.size
fox
.save_screenshot('screenshot.png') # saves screenshot of entire page
fox
.quit()
im
= Image.open('screenshot.png') # uses PIL library to open image in memory
left
= location['x']
top
= location['y']
right
= location['x'] + size['width']
bottom
= location['y'] + size['height']
im
= im.crop((left, top, right, bottom)) # defines crop points
im
.save('screenshot.png') # saves new cropped image

and the finally output is…. drum roll the Stackoverflow logo!!!

enter image description here

now of course this would be overkill for just grabbing a static image but if your want to grab something that requires Javascript to get to this could be a viable solution.

  • You must to post comments
Showing 1 result
Your Answer
Post as a guest by filling out the fields below or if you already have an account.
Name*
E-mail*
Website