linkapi.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from hytest import *
  2. from playwright.sync_api import sync_playwright
  3. from PIL import Image, ImageChops
  4. class APILink():
  5. def setup(self):
  6. # 初始化 Playwright
  7. self.playwright = sync_playwright().start()
  8. self.browser = self.playwright.chromium.launch(headless=True)
  9. self.page = self.browser.new_page()
  10. def teardown(self):
  11. # 关闭浏览器
  12. self.browser.close()
  13. self.playwright.stop()
  14. #网页截图模糊遮罩方法,适用于网页有动态元素,进行遮罩比较
  15. def save_screenshot_mask(self,url, output_path, elements, clip=None):
  16. locs = []
  17. self.page.goto(url)
  18. for element in elements:
  19. loc = self.page.locator(element)
  20. locs.append(loc)
  21. self.page.screenshot(path=output_path,mask=locs, clip=clip)
  22. #网页直接截图方法,适用于网页元素不变,可直接截图比较
  23. def save_screenshot(self,url, output_path, clip=None):
  24. self.page.goto(url)
  25. self.page.screenshot(path=output_path, clip=clip)
  26. def compare_images(self, image1_path, image2_path):
  27. image1 = Image.open(image1_path)
  28. image2 = Image.open(image2_path)
  29. diff = ImageChops.difference(image1, image2)
  30. if diff.getbbox() is None:
  31. INFO("两张图片完全相同")
  32. return True
  33. else:
  34. INFO("两张图片存在差异")
  35. return False
  36. #对比样本快照与当前快照
  37. def contrast_snapshot(self,url,expected_screenshot,current_screenshot,element,clip):
  38. # 如果不存在样本照片,生成样本照片
  39. self.save_screenshot(url, expected_screenshot,element,clip)
  40. INFO(f"样本快照已保存:{expected_screenshot}")
  41. #生成对比照片
  42. apilink.save_screenshot(url, current_screenshot,element,clip)
  43. INFO(f"对比快照已保存:{expected_screenshot}")
  44. #返回对比结果
  45. result = apilink.compare_images(current_screenshot, expected_screenshot)
  46. return result
  47. apilink = APILink()