How to call Capture Page Screenshot keyword within robot framework listener

214 views
Skip to first unread message

Jagadish Chandran

unread,
Jun 7, 2016, 12:12:15 PM6/7/16
to robotframework-users
I want to capture page screen shot for failed test cases. I want this to be implemented in Robot framework listener (end_test). I have previously setting a suite variable from the listener (start_suite) like BuiltIn().set_suite_variable('${Password}', xxxxx) by importing (from robot.libraries.BuiltIn import BuiltIn). Now looking for similar solution to capture page screen shot.

Kevin O.

unread,
Jun 7, 2016, 5:28:58 PM6/7/16
to robotframework-users
If you are closing the browser in a test teardown, as is usually the case, then it is too late to take a screenshot.
If you defer to the listener for cleanup, then you could get this to work.
Here is a listener that will take a screenshot if the test failed and also close all browsers if appropriate. Capturing a screenshot can raise an exception and that is not handled here.

from robot.libraries.BuiltIn import BuiltIn

class MyListener(object):

    ROBOT_LISTENER_API_VERSION = 2

    def end_test(self, name, attrs):
        s2l = None
        try:
            s2l = BuiltIn().get_library_instance('Selenium2Library')
        except RuntimeError:
            print "Selenium2Library is not in use"
        if s2l and attrs['status'] != 'PASS':
            driver = None
            try:
                driver = s2l._current_browser()
            except RuntimeError:
                print "No browser open, skipping screenshot"
            if driver:
                s2l.capture_page_screenshot() 
        if s2l:
            s2l.close_all_browsers() # safe even if no browser is open

Jagadish Chandran

unread,
Jun 8, 2016, 4:43:20 AM6/8/16
to robotframework-users
Thanks a lot Kevin. This is what exactly I am looking for.
Reply all
Reply to author
Forward
0 new messages