selenium 长截图

最近需要对网页进行整体截图

找了很多方法

1,打印另存为pdf

2,调整界面大小截图

测试下来,打印另存pdf可以,但是排版有点不太一样,而且配置比较麻烦,还需要用到pywin32对弹出得保存框进行确认

调整界面大小截图,这个无法实现,高度调不了太大

找了一下,发现chrome提供这个长截图:Capture full size screenshot

找了一下有人提供了方法,进行一些封装后就能直接使用了

def save_full_screen(file_name):
    # 取出页面的宽度和高度
    page_width = driver.execute_script("return document.body.scrollWidth")
    page_height = driver.execute_script("return document.body.scrollHeight")
    # 直接开启设备模拟,不要再手动开devtools了,否则截图截的是devtools的界面!
    driver.execute_cdp_cmd('Emulation.setDeviceMetricsOverride', {'mobile':False, 'width':page_width, 'height':page_height, 'deviceScaleFactor': 1})
    # 执行截图
    res = driver.execute_cdp_cmd('Page.captureScreenshot', { 'fromSurface': True})
    time.sleep(0.5)
    # 返回的base64内容写入PNG文件
    with open(file_name, 'wb') as f:
        img = base64.b64decode(res['data'])
        f.write(img)
    # 关闭设备模拟
    driver.execute_cdp_cmd('Emulation.clearDeviceMetricsOverride', {})

  原文链接:https://blog.csdn.net/qq_35977139/article/details/111552903

 这种方法比较方便,直接截图完成

原文地址:https://www.cnblogs.com/darkspr/p/14504096.html