Selenium Screenshot Works Slow (Python)Ask Question


Script with selenium and phantomjs which checks around 20 dynamic pages and warn me when there is a change works fast without screenshot part but when I want to get screenshots of the pages it takes around 1-2 minutes to warn me and to get screenshot. Is there a better and faster way to take screenshot of a specific part of page with python?

Here is the code I use for screenshot.

from selenium import webdriver
from PIL import Image

fox = webdriver.Firefox()

# 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

im ='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'screenshot.png') # saves new cropped image


The problem is not about selenium module, either screenshot. It is about phantomjs, after I start using chromedriver it is very fast and more efficent.


The problem with phantomjs is disabling images. When I use --load-images=no I face with the memory leak issue and scripts gets really slower, without it there is no problem.


You could save some time by cropping the screenshot in memory without saving it first to a file:

import StringIO
from selenium import webdriver
from PIL import Image

driver = webdriver.Firefox()
element = driver.find_element_by_id('hlogo')

crop_points = driver.execute_script("""
    var r = arguments[0].getBoundingClientRect();
    return [r.left,, r.left + r.width, + r.height];
    """, element)

with as img :
    with img.crop(crop_points) as imgsub :', 'PNG')
标签: performance selenium phantomjs screenshot
© 2014 TuiCode, Inc.