Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take partial screenshot with Selenium WebDriver in python?

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?

like image 442
streamoverflowed Avatar asked Feb 22 '13 06:02

streamoverflowed


People also ask

How do you take a screenshot of a specific area in Selenium Python?

For capturing the screenshot, save_screenshot() method is available. This method takes the full page screenshot. There is no in built method to capture an element. To achieve this we have to crop the image of the full page to the particular size of the element.

How do you take a screenshot of a selected area in Python?

You can use pyscreenshot module. The pyscreenshot module can be used to copy the contents of the screen to a PIL image memory or file. You can install it using pip .


2 Answers

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

from selenium import webdriver
from PIL import Image
from io import BytesIO

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
png = fox.get_screenshot_as_png() # saves screenshot of entire page
fox.quit()

im = Image.open(BytesIO(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 finally the output is... 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.

like image 64
RandomPhobia Avatar answered Oct 28 '22 18:10

RandomPhobia


Worked for me in python3.5

from selenium import webdriver


fox = webdriver.Firefox()
fox.get('http://stackoverflow.com/')
image = fox.find_element_by_id('hlogo').screenshot_as_png

p.s.

To save to file

image=driver.find_element_by_id('hlogo').screenshot(output_file_path)
like image 30
Iman Kermani Avatar answered Oct 28 '22 17:10

Iman Kermani