def get_screen(self, name="截图", switch=True): print(datetime.datetime.now(), name) if switch is False: return im = Image.open(BytesIO(self.driver.get_screenshot_as_png())) # Image加载截图bytes数据流 size = (im.size[0] / 3, im.size[1] / 3) # 根据截图大小计算压缩后截图分辨率 im.thumbnail(size) # 图片压缩 temp = BytesIO() # 初始化二进制流 im.save(temp, 'png') # 将图片数据写入至二进制数据流 im_bytes = temp.getvalue() # 读取二进制流 (将img数据类型转化为bytes数据类型) allure.attach(name, im_bytes, allure.attach_type.PNG)
# 图片对比定位元素 def find_pic(self, loc: dict, times=8, switch=True): """ :param loc:图片名称列表及元素大概位置(可选项) 'name': '返回键', 'ios_pic': ('back_ios.png', 'back2_ios.png'[, (0, 0, 0.15, 0.1)]) 位置:x1, y1, x2, y2 左上点坐标及左下点坐标基于全图的相对位置,增加对比准确度 :param times: :param switch: :return: 返回定位中心点坐标 """ pic_source = source_path + 'pages/source/' crop = False if type(loc['ios_pic'][-1]) == tuple: crop = True for i in range(times): for pic in loc['ios_pic']: if type(pic) == tuple: continue target = ac.imread(pic_source + pic) im = Image.open(BytesIO(self.driver.get_screenshot_as_png())) px_w, px_h = im.size pt_h = self.driver.get_window_size()['height'] scale_factor = px_h / pt_h # 缩放率 udid = pic_source + 'temp/%s.png' % self.udid if crop: x1, y1, x2, y2 = loc['ios_pic'][-1] im.crop((px_w * x1, px_h * y1, px_w * x2, px_h * y2)).save(udid, 'png') else: im.save(udid, 'png') temp = ac.imread(udid) pos = ac.find_template(temp, target) print(loc['name'], pos) if pos is None: time.sleep(1) continue (x, y) = pos['result'] if crop: ret = ((x + px_w * x1) / scale_factor, (y + px_h * y1) / scale_factor) else: ret = (x / scale_factor, y / scale_factor) self.get_screen('%s定位成功截图' % loc['name'], switch) return ret else: self.get_screen('%s定位失败截图' % (loc['name']), switch) raise