def take_screenshot(self):
    """Take a screenshot after a failed step."""

    if not self.failed:
        return

    browser = getattr(world, 'browser', None)
    if not browser:
        return

    try:
        scenario_name = self.scenario.name
        scenario_index = \
            self.scenario.feature.scenarios.index(self.scenario) + 1
    except AttributeError:
        scenario_name = self.background.keyword
        scenario_index = 0

    if self.outline is None:
        outline_index_str = ''
    else:
        outline_index = self.scenario.outlines.index(self.outline) + 1
        outline_index_str = '_{}'.format(outline_index)

    base_name = FORMAT.format(
        feature_file=os.path.relpath(self.feature.filename),
        scenario_index=scenario_index,
        scenario_name=scenario_name,
        outline_index=outline_index_str,
    )
    base_name = re.sub(r'\W', '_', base_name, flags=re.UNICODE)
    base_name = os.path.join(DIRECTORY, base_name)

    world.browser.save_screenshot('{}.png'.format(base_name))

    with open('{}.html'.format(base_name), 'w') as page_source_file:
        page_source_file.write(world.browser.page_source)
Take a screenshot after a failed step.