Selenium 截全屏
Selenium 截全屏
当使用Selenium进行自动化测试时,有的时候需要截取网页的全部内容,但是Selenium自带的截屏函数save_screenshot()只能截取部分图片,网上也有先滚动页面再拼接的函数,但是会有重复的部分,而且需要根据页面设置参数。下面这种方法避免了上述问题,写下来避免遗忘。
def save_fullscreenshot(driver,screen_shot_name):
# We need the dimensions of the content
page_rect = driver.execute_cdp_cmd('Page.getLayoutMetrics', {})
# parameters needed for ful page screenshot
# note we are setting the width and height of the viewport to screenshot, same as the site's content size
screenshot_config = {'captureBeyondViewport': True,
'fromSurface': True,
'clip': {'width': page_rect['contentSize']['width'],
'height': page_rect['contentSize']['height'],
'x': 0,
'y': 0,
'scale': 1},
}
# Dictionary with 1 key: data
base_64_png = driver.execute_cdp_cmd('Page.captureScreenshot', screenshot_config)
# Write img to file
with open(screen_shot_name, "wb") as fh:
fh.write(base64.urlsafe_b64decode(base_64_png['data']))
结果