阿里RPA长控件截图
应用背景
用RPA的Chrome模块的screenshot方法给控件截图,有时控件太长超出屏幕高度造成截图不完整,尝试滚动截图
应到的环境及工具
rpa3,python3
思路
分段截屏,最后拼接
代码(Python)
from rpa.core import *
from rpa.utils import *
import rpa3 as rpa # 使用V3引擎
import os
from PIL import Image
# 可能还需要其他引用……
"""
元素长截图时,分段截图最后拼接,默认每次取614高度
page : rpa.chrome.catch('捕获的页面')
imgPath : r 'D:\保存图片的地址.png'
截图区域 : 提前录制的控件
"""
def getLongImg(page,imgPath):
sc_hight = 614 # 每段截屏的高度
pos = page.pos('截图区域', index = 1) # 获取控件‘截图区域’的坐标
height = pos['y2']- pos['y1'] # 高
width = pos['x2']- pos['x1'] # 宽
count = int(height / sc_hight) # 元素的高度除以你每次截多少就是次数
start_higth = 0 # 元素的初始高度
max_px = start_higth + (count - 1) * sc_hight # for循环中最大的px
last_px = height + start_higth - sc_hight # 元素最底部的位置
surplus_px = last_px - max_px # 剩余的边的高度
img_path = [] # 用来存放图片地址
for i in range(0, count + 1):
if i == count:
page.scroll() # 最后一次直接划到最底部
elif i > 0:
page.scroll(sc_hight*i) # 用于移动滑轮,每次移动614px,初始值是元素的初始高度
sleep(0.5)
fp = r"D:\临时图片存放\%s.png" % i # 图片地址,运行的话,改一下
page.screenshot('截图区域', fp) # 屏幕截图,这里是截取是完整的控件图片
img = Image.open(fp=fp)
y2 = sc_hight * (i+1)
if y2 > height:
y2 = height
rpa.logger.info('剪切图片参数:{},{},{},{}'.format(0, sc_hight * i,width, y2))
if sc_hight * i < y2:
img2 = img.crop((0, sc_hight * i,width, y2)) # 剪切图片
img2.save(fp) # 保存图片,覆盖完整的网页图片
img_path.append(fp) # 添加图片路径
sleep(0.5)
new_img = Image.new("RGB", (width, height)) # 创建一个新图片,大小为元素的大小
k = 0
for i in img_path:
tem_img = Image.open(i)
new_img.paste(tem_img, (0, sc_hight * k)) # 把图片贴上去,间隔一个截图的距离
k += 1
else:
new_img.save(imgPath) # 保存
pass
参考文章
https://www.cnblogs.com/98WDJ/archive/2019/11/13/11851140.html