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