|
| 1 | +from robot.libraries.BuiltIn import BuiltIn |
| 2 | +from SeleniumLibrary.base import LibraryComponent, keyword |
| 3 | + |
| 4 | + |
| 5 | +try: |
| 6 | + import cv2 |
| 7 | +except ImportError: |
| 8 | + cv2 = None |
| 9 | + |
| 10 | +try: |
| 11 | + from PIL import Image |
| 12 | +except ImportError: |
| 13 | + Image = None |
| 14 | + |
| 15 | + |
| 16 | +class ScreenshotKeywords(LibraryComponent): |
| 17 | + @keyword |
| 18 | + def capture_element_screenshot(self, locator, filename, embed=True): |
| 19 | + el = self.find_element(locator) |
| 20 | + BuiltIn().run_keyword("Capture Page Screenshot", filename) |
| 21 | + rect = {**el.location, **el.size} |
| 22 | + self.crop_image(filename, **self.round_dict(rect)) |
| 23 | + |
| 24 | + def round_dict(self, dict): |
| 25 | + return { |
| 26 | + k: int(round(v)) if isinstance(v, float) else v for k, v in dict.items() |
| 27 | + } |
| 28 | + |
| 29 | + @keyword |
| 30 | + def crop_image(self, in_file, x, y, width, height, out_file=None): |
| 31 | + if cv2: |
| 32 | + return self.crop_with_opencv(in_file, x, y, width, height, out_file) |
| 33 | + elif Image: |
| 34 | + return self.crop_with_pillow(in_file, x, y, width, height, out_file) |
| 35 | + |
| 36 | + def crop_with_opencv(self, in_file, x, y, width, height, out_file=None): |
| 37 | + out_file = out_file or in_file |
| 38 | + im = cv2.imread(in_file) |
| 39 | + im = im[int(y) : int(y + height), int(x) : int(x + width)] |
| 40 | + cv2.imwrite(out_file, im) |
| 41 | + return out_file |
| 42 | + |
| 43 | + def crop_with_pillow(self, in_file, x, y, width, height, out_file=None): |
| 44 | + out_file = out_file or in_file |
| 45 | + img = Image.open(in_file) |
| 46 | + area = img.crop((int(x), int(y), int(x + width), int(y + height))) |
| 47 | + |
| 48 | + with open(out_file, "wb") as output: |
| 49 | + area.save(output, "png") |
| 50 | + |
| 51 | + return out_file |
0 commit comments