linkapi.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. from hytest import *
  2. from playwright.sync_api import sync_playwright
  3. from PIL import Image, ImageChops
  4. from bs4 import BeautifulSoup
  5. import requests
  6. class APILink():
  7. #打开链接
  8. def open_url(self,url):
  9. response = requests.get(url)
  10. response.encoding = 'utf-8' # 设置编码为gbk
  11. soup = BeautifulSoup(response.text, 'html.parser')
  12. title = soup.title.string
  13. return title
  14. def setup(self):
  15. # 初始化 Playwright
  16. self.playwright = sync_playwright().start()
  17. self.browser = self.playwright.chromium.launch(headless=True)
  18. self.page = self.browser.new_page()
  19. def teardown(self):
  20. # 关闭浏览器
  21. self.browser.close()
  22. self.playwright.stop()
  23. #网页截图模糊遮罩方法,适用于网页有动态元素,进行遮罩比较
  24. def save_screenshot_mask(self,url, output_path, elements, clip=None):
  25. locs = []
  26. self.page.goto(url)
  27. for element in elements:
  28. loc = self.page.locator(element)
  29. locs.append(loc)
  30. self.page.screenshot(path=output_path,mask=locs, clip=clip)
  31. #网页直接截图方法,适用于网页元素不变,可直接截图比较
  32. def save_screenshot(self,url, output_path, clip=None):
  33. self.page.goto(url)
  34. self.page.screenshot(path=output_path, clip=clip)
  35. def compare_images(self, image1_path, image2_path):
  36. image1 = Image.open(image1_path)
  37. image2 = Image.open(image2_path)
  38. diff = ImageChops.difference(image1, image2)
  39. if diff.getbbox() is None:
  40. INFO("两张图片完全相同")
  41. return True
  42. else:
  43. INFO("两张图片存在差异")
  44. return False
  45. #对比样本快照与当前快照
  46. def contrast_snapshot(self,url,expected_screenshot,current_screenshot,clip):
  47. # 如果不存在样本照片,生成样本照片
  48. if not os.path.exists(expected_screenshot):
  49. self.save_screenshot(url, expected_screenshot,clip)
  50. INFO(f"样本快照已保存:{expected_screenshot}")
  51. #生成对比照片
  52. apilink.save_screenshot(url, current_screenshot,clip)
  53. INFO(f"对比快照已保存:{expected_screenshot}")
  54. #返回对比结果
  55. result = apilink.compare_images(current_screenshot, expected_screenshot)
  56. return result
  57. #对比样本快照与当前快照2
  58. def contrast_snapshot_mask(self,url,expected_screenshot,current_screenshot,element,clip):
  59. # 如果不存在样本照片,生成样本照片
  60. if not os.path.exists(expected_screenshot):
  61. self.save_screenshot_mask(url, expected_screenshot,element,clip)
  62. INFO(f"样本快照已保存:{expected_screenshot}")
  63. #生成对比照片
  64. apilink.save_screenshot_mask(url, current_screenshot,element,clip)
  65. INFO(f"对比快照已保存:{expected_screenshot}")
  66. #返回对比结果
  67. result = apilink.compare_images(current_screenshot, expected_screenshot)
  68. return result
  69. apilink = APILink()