linkapi.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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,clip):
  38. # 如果不存在样本照片,生成样本照片
  39. if not os.path.exists(expected_screenshot):
  40. self.save_screenshot(url, expected_screenshot,clip)
  41. INFO(f"样本快照已保存:{expected_screenshot}")
  42. #生成对比照片
  43. apilink.save_screenshot(url, current_screenshot,clip)
  44. INFO(f"对比快照已保存:{expected_screenshot}")
  45. #返回对比结果
  46. result = apilink.compare_images(current_screenshot, expected_screenshot)
  47. return result
  48. #对比样本快照与当前快照2
  49. def contrast_snapshot_mask(self,url,expected_screenshot,current_screenshot,element,clip):
  50. # 如果不存在样本照片,生成样本照片
  51. if not os.path.exists(expected_screenshot):
  52. self.save_screenshot_mask(url, expected_screenshot,element,clip)
  53. INFO(f"样本快照已保存:{expected_screenshot}")
  54. #生成对比照片
  55. apilink.save_screenshot_mask(url, current_screenshot,element,clip)
  56. INFO(f"对比快照已保存:{expected_screenshot}")
  57. #返回对比结果
  58. result = apilink.compare_images(current_screenshot, expected_screenshot)
  59. return result
  60. apilink = APILink()