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?
Advertisement
Answer
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 install it with pip install Pillow
JavaScript
x
25
25
1
from selenium import webdriver
2
from PIL import Image
3
from io import BytesIO
4
5
fox = webdriver.Firefox()
6
fox.get('http://stackoverflow.com/')
7
8
# now that we have the preliminary stuff out of the way time to get that image :D
9
element = fox.find_element_by_id('hlogo') # find part of the page you want image of
10
location = element.location
11
size = element.size
12
png = fox.get_screenshot_as_png() # saves screenshot of entire page
13
fox.quit()
14
15
im = Image.open(BytesIO(png)) # uses PIL library to open image in memory
16
17
left = location['x']
18
top = location['y']
19
right = location['x'] + size['width']
20
bottom = location['y'] + size['height']
21
22
23
im = im.crop((left, top, right, bottom)) # defines crop points
24
im.save('screenshot.png') # saves new cropped image
25
and finally the output is… the Stackoverflow logo!!!
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.