Splinter crashes when using screenshot with pillow with full=True
I am trying to take a screenshot of the nav element with:
self.browser.find_by_css("nav").first.screenshot('/tmp/nav_screenshot.png', full=True)
which should be pretty much the example in the docs (using css rather than xpath find).
Full traceback:
self = <splinter.driver.webdriver.WebDriverElement object at 0x7feb34c09c18>
name = '/tmp/nav_screenshot.png', suffix = '.png', full = True
def screenshot(self, name='', suffix='.png', full=False):
name = name or ''
(fd, filename) = tempfile.mkstemp(prefix=name, suffix=suffix)
# don't hold the file
os.close(fd)
if full:
ori_window_size = self.driver.get_window_size()
> self._full_screen()
E TypeError: _full_screen() takes 0 positional arguments but 1 was given
/usr/local/lib/python3.6/dist-packages/splinter/driver/webdriver/__init__.py:951: TypeError
OS: Ubuntu 18.04.5 LTS Python: 3.6.9 splinter: 0.14.0 Pillow: 7.2.0 (installed via pip after removing python3-pil package)
Two things to note about "nav":
- It is a column on the left hand side of the screen.
- It starts in the viewport and extends outside.
trying to screenshot it without full=True results in: SystemError: tile cannot extend outside image
Hmph. Looks like bad def of _full_screen in init.py:
def _full_screen():
width = self.driver.execute_script("return Math.max(document.body
.scrollWidth, document.body.offsetWidth);")
height = self.driver.execute_script("return Math.max(document.bod
y.scrollHeight, document.body.offsetHeight);")
self.driver.set_window_size(width, height)
Editing this to:
def _full_screen(self):
(and clearing the file from the cache)
makes it blow up further down in /usr/local/lib/python3.6/dist-packages/PIL/ImageFile.py:514 with:
SystemError: tile cannot extend outside image
Any ideas?
Thanks.
-- rouilj
#810 will fix the issue with the method crashing.
Will #810 fix the SystemError as well?
Doubt it. If you can reproduce the issue on a publicly accessible web page then I can try to reproduce it locally.
In message cobrateam/splinter/issues/808/[email protected], Joshua Fehler writes:
Doubt it. If you can reproduce the issue on a publicly accessible web page then I can try to reproduce it locally.
With the attached script I get:
============================= test session starts ============================== platform linux -- Python 3.6.9, pytest-6.0.2, py-1.9.0, pluggy-0.13.1 -- /usr/bi n/python3 cachedir: .pytest_cache rootdir: /home/rouilj/develop/splinter collecting ... collected 1 item
demo_test.py::TestSysadminTracker::test_tracker FAILED
=================================== FAILURES =================================== _______________________ TestSysadminTracker.test_tracker _______________________
im = <PIL.Image.Image image mode=RGBA size=1200x0 at 0x7F796D7B5E48> fp = <PIL.PngImagePlugin._idat object at 0x7f796bdcb278> tile = [('zip', (0, 0, 1200, 0), 0, 'RGBA')], bufsize = 65536
def _save(im, fp, tile, bufsize=0):
"""Helper to save image based on tile list
:param im: Image object.
:param fp: File object.
:param tile: Tile list.
:param bufsize: Optional buffer size
"""
im.load()
if not hasattr(im, "encoderconfig"):
im.encoderconfig = ()
tile.sort(key=_tilesort)
# FIXME: make MAXBLOCK a configuration parameter
# It would be great if we could have the encoder specify what it needs
# But, it would need at least the image size in most cases. RawEncode is
# a tricky case.
bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c
if fp == sys.stdout:
fp.flush()
return
try:
fh = fp.fileno()
E AttributeError: '_idat' object has no attribute 'fileno'
/usr/local/lib/python3.6/dist-packages/PIL/ImageFile.py:506: AttributeError
During handling of the above exception, another exception occurred:
self = <demot_test2.TestSysadminTracker testMethod=test_tracker>
def test_tracker(self):
browser=self.browser
browser.visit("https rouilj dot .dynamic-dns.net/demo")
# screenshot the menu - element screenshotting broken
ssp = browser.find_by_css("nav").first.screenshot(directory + '/ss_menu_')
demot_test2.py:80:
/usr/local/lib/python3.6/dist-packages/splinter/driver/webdriver/init.py:961: in screenshot target.save(filename) /usr/local/lib/python3.6/dist-packages/PIL/Image.py:2158: in save save_handler(self, fp, filename) /usr/local/lib/python3.6/dist-packages/PIL/PngImagePlugin.py:1284: in _save ImageFile._save(im, _idat(fp, chunk), [("zip", (0, 0) + im.size, 0, rawmode)])
im = <PIL.Image.Image image mode=RGBA size=1200x0 at 0x7FF95F0222B0> fp = <PIL.PngImagePlugin._idat object at 0x7ff95d58f358> tile = [('zip', (0, 0, 1200, 0), 0, 'RGBA')], bufsize = 65536
def _save(im, fp, tile, bufsize=0):
"""Helper to save image based on tile list
:param im: Image object.
:param fp: File object.
:param tile: Tile list.
:param bufsize: Optional buffer size
"""
im.load()
if not hasattr(im, "encoderconfig"):
im.encoderconfig = ()
tile.sort(key=_tilesort)
# FIXME: make MAXBLOCK a configuration parameter
# It would be great if we could have the encoder specify what it needs
# But, it would need at least the image size in most cases. RawEncode is
# a tricky case.
bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c
if fp == sys.stdout:
fp.flush()
return
try:
fh = fp.fileno()
fp.flush()
except (AttributeError, io.UnsupportedOperation) as e:
# compress to Python file-compatible object
for e, b, o, a in tile:
e = Image._getencoder(im.mode, e, a, im.encoderconfig)
if o > 0:
fp.seek(o)
e.setimage(im.im, b)
E SystemError: tile cannot extend outside image
/usr/local/lib/python3.6/dist-packages/PIL/ImageFile.py:514: SystemError =========================== short test summary info ============================ FAILED demot_test2.py::TestSysadminTracker::test_tracker - SystemError: tile ... ============================== 1 failed in 10.68s ==============================
(Note I edited the URL so it's not indexed.)
-- -- rouilj John Rouillard
My employers don't acknowledge my existence much less my opinions.
In commit: https://github.com/cobrateam/splinter/commit/daa3ed97d7bd838fcc6cfe56f78f98f223971e76 a test of screenshotting an element is made using the body element. If you modify my test script to use the body rather than the nav element, it completes without error. My guess is some calculation for the bounding box for nav is wrong and the browser window is not being resized properly to encompass the whole nav element. However the resize does work well for the body element.
Crud it looks like attachments to email don't get incorporated into the issue. And I can't attach the file either. Failing processing. Let's try inlining it:
import unittest, time, os
from splinter import Browser
# required as setting options for chrome driver using list doesn't work.
from selenium.webdriver.chrome.options import Options
# allow typing keys like escape, page down enter etc.
from selenium.webdriver.common.keys import Keys
directory=os.getcwd() +'/images'
class TestSysadminTracker(unittest.TestCase):
@classmethod
def setUpClass(cls):
# allow choice of browser from env var
use = os.environ.get("BROWSER", default="chrome")
if use not in [ "firefox", "chrome" ]:
print("BROWSER env var is %s: not one of firefox or chrome"%use)
assert False # abort test framework
if use == 'chrome':
options = Options()
# must set size, defaults to 768 px size which triggers
# tablet/phone mode
options.add_argument('--window-size=1280,1696')
cls.browser = Browser('chrome', headless=True, fullscreen=True,
options=options)
elif use == "firefox":
cls.browser = Browser('firefox', headless=True, fullscreen=True)
@classmethod
def tearDownClass(cls):
cls.browser.quit()
def do_login_if_needed(self, username, password):
# look for login form
if self.browser.is_element_present_by_css("#login"):
self.browser.fill("__login_name", username)
self.browser.fill("__login_password", password)
self.browser.find_by_css(
'#login input[type="submit"]').first.click()
# should have one logout link in nav section, otherwise
# login failed.
time.sleep(2)
self.assertTrue(len(self.browser.find_by_css('nav').links.find_by_text('Logout')) == 1)
def do_logout_if_needed(self):
logout = self.browser.find_by_css('nav').links.find_by_text('Logout')
self.assertIn( len(logout), (0, 1) ) # if > 1 we have an issue
if len(logout) == 1:
logout.first.click() # log me out
time.sleep(5) # FIXME why do I need an explicit delay
# should have zero logout links, otherwise logout failed.
logout = self.browser.find_by_css('nav').links.find_by_text('Logout')
self.assertTrue(len(logout) == 0)
return
elif len(logout) == 0:
return
assert(False) # not reached unless something is very wrong
def waitfor(self, css):
waiting_for = self.browser.find_by_css(css).first
while not waiting_for.visible:
# waits for the JavaScript to put the button on the page
pass
return waiting_for
def test_tracker(self):
browser=self.browser
browser.visit("https://rouilj.dynamic-dns.net/demo")
# screenshot the menu - element screenshotting broken
ssp = browser.find_by_css("nav").first.screenshot(directory + '/ss_menu_')
print(ssp)
@rouilj This issue is occurring because the nav element is larger than the size of the screen. The crop then fails because you can't crop something larger than the original image.
The nav element in your use case will always resize to be larger than the screen size. ie: It will always fail.
This isn't an issue with splinter or pillow, it's an issue with the element.
Hi Joshua:
In message cobrateam/splinter/issues/808/[email protected], Joshua Fehler writes:
@rouilj This issue is occurring because the
navelement is larger than the size of the screen. The crop then fails because you can't crop something larger than the original image.The
navelement in your use case will always resize to be larger than the screen size. ie: It will always fail.This isn't an issue with splinter or pillow, it's an issue with the element.
Isn't that what full=True is supposed to fix? The test also fails with:
ssp = browser.find_by_css("nav").first.screenshot(directory + '/ss_menu_', full=True)
as well. I thought full was supposed to resize the browser window to encompass the whole element/page. I removed it from the example to simplify the test since it had no effect.
If I use:
browser.screenshot(directory + '/ss_index1_', full=True)
to screenshot the whole page including the nav element, the nav element is properly captured. So I can indeed get a screenshot of the whole nav element just not as an isolated element.
In any case, the javascript I put at the bottom of the page tells me that whole page size is:
w: 1265px h: 1863px
I start chrome with '--window-size=1280,1696' (which matches the document window height/width) and I think is longer than the nav element.
If your explantion is correct, I should be able to resize the browser/screen to display the entire page. If I use:
browser.driver.set_window_size(1280,2000)
just before the call to:
ssp = browser.find_by_css("nav").first.screenshot(directory + '/ss_menu_')
then entire nav element should be on the screen. I did that and screenshotting the whole page (using full=True) I confirmed that the window width and height are 1280 and 2000 the same as the document height and width (1).
But screenshotting the element after using set_window_size as above the crash still occurs.
I am using this script to capture screenshots for a manual. I really can't slice and dice the full image using image processing tools as a change to the nav column (eg. adding a new search, or showing the nav column after login) would require new hard coded values for the cropping rectangle.
(I'll try attaching the png screenshot in (1). Let's see if it works.)
-- -- rouilj John Rouillard
My employers don't acknowledge my existence much less my opinions.
Ok here is the page screenshot I hope.

@rouilj I misunderstood the nature of why the element values were wrong, but I've discovered what's actually causing your issue. It's the 0px height on the nav element. You're trying to do a crop with 0 as the height and pillow can't handle that.
If you do: browser.execute_script("document.getElementsByTagName('nav')[0].style.height = '1px';") then it won't crash.
In your particular case, you'd be better off trying to capture the div inside the nav.
Hi Joshua:
In message cobrateam/splinter/issues/808/[email protected], Joshua Fehler writes:
@rouilj I misunderstood the nature of why the element values were wrong, but I've discovered what's actually causing your issue. It's the 0px height on the nav element. You're trying to do a crop with 0 as the height and pillow can't handle that.
If you do:
browser.execute_script("document.getElementsByTagName('nav')[0].style.height = '1px';")then it won't crash.In your particular case, you'd be better off trying to capture the
divinside thenav.
Wow. I see the 0px height for nav in the chrome devtools computed values tab. WTH. That sounds like a bug in chrome. Firefox doesn't show a computed height at all for nav which is also odd.
As you point out 'nav > div[role="navigation"]' has a non-zero height. Why isn't that height propagated up to the enclosing nav element???
The main tag has a div inside it. The main tag has a non-zero height (the same height as the div). Structurally this is the same construct as the nav. So strange. Do you have another explanation than a bug in chrome?
Adding css:
nav { height: 1px }
or
nav { min-height: 1px }
and screenshotting the 'nav' displays a single red line 1px in height. So not exactly useful.
Using 'nav > div' as the selector properly captures the menu. I could also use 'div[role="navigation"]' I suppose. Bummer I can't use the nav tag though.
Thanks for diagnosing what was happening there. That's an odd one.
Is it possible in splinter to detect that the height (or width) of n element is 0 and raise a suitable error? Does splinter defer that all to the underlying driver?
A suitable error like:
element nav has 0 height and an image can not be created.
would go a long way to giving me a clue.
-- -- rouilj John Rouillard
My employers don't acknowledge my existence much less my opinions.
@rouilj CSS doesn't work like that. HTML is a markup language for documents, not a UI kit. Elements don't actually have a real width or height or any other CSS properties. You can have a child that's styled to be physically larger than the parent and that's fine. The parent conceptually contains the child, but physically it can be anywhere on the page if you style it.
At least, that's the way I understand it.
I'm closing this issue since everything is solved, but you can file another one for raising a nicer exception when trying to screenshot an element with a 0px width/height.
This bug also affects me, but the fix wasn't released yet. Do you have plans to release it as 0.14.1 or 0.15.0 in the following days?