seleniumwire如何截长图

最近研究控制Chrome API来进行自动截图的方法。然后就看到了博客园的文章https://www.cnblogs.com/superhin/archive/2004/01/13/11481910.html 。文章说Selenium并不支持对整个页面截图,原因是Chrome虽然在开发者工具中提供了“Capture full size screenshot”的Run Command,但是在CDP中并没有提供executeCdpCommand的命令。
为了解决这个问题,鄙人把Chromium的源代码扒了出来,然后看到这个“Capture full size screenshot”实际上走的是先设置了一个设备模拟把高度调成和页面高度一样,然后再截当前屏幕截图。
鄙人也留意了一下国外的编程社区,发现国外基本上也是这么干的,临时设置了一个设备模拟,然后截当前屏幕的截图,截好图了再把设备模拟关闭。
这样的话使用Python语言操作如下:

from selenium import webdriver
from time import sleep
import base64
 
# 接入既有的浏览器进程
options = webdriver.ChromeOptions()
options.debugger_address = "127.0.0.1:9222"
driver = webdriver.Chrome(options=options)
 
# 取出页面的宽度和高度
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})
 
# 返回的base64内容写入PNG文件
with open('hao123.png', 'wb') as f:
    img = base64.b64decode(res['data'])
    f.write(img)
 
# 等待截图完成
sleep(15)
 
# 关闭设备模拟
driver.execute_cdp_cmd('Emulation.clearDeviceMetricsOverride', {})

上面的代码,亲测有效,可以在windows中正常的截取长图。 但是如果部署在linux操作系统中,即使我添加了headless无头模式,还是依然无法实现截取全图,

最后就就只能在window上执行了。

如果你还想读取上面截取的长图,代码如下就可以获取图片:

 # Read image
 image = open(image_name, "rb")
 data = image.read()
 str_output = str(base64.b64encode(data), "utf-8") #str_output就是读取到的图片内容 

 

如果阁下有方案解决在linux中也能截取长图,欢迎私信分享,感谢!

参考:https://www.cnblogs.com/wujiuqier/articles/17708073.html

posted @ 2024-09-04 13:54  苹果芒  阅读(48)  评论(0编辑  收藏  举报