from hytest import * from playwright.sync_api import sync_playwright from PIL import Image, ImageChops from bs4 import BeautifulSoup import requests class APILink(): #打开链接 def open_url(self,url): response = requests.get(url) response.encoding = 'utf-8' # 设置编码为gbk soup = BeautifulSoup(response.text, 'html.parser') title = soup.title.string return title def setup(self): # 初始化 Playwright self.playwright = sync_playwright().start() self.browser = self.playwright.chromium.launch(headless=True) self.page = self.browser.new_page() def teardown(self): # 关闭浏览器 self.browser.close() self.playwright.stop() #网页截图模糊遮罩方法,适用于网页有动态元素,进行遮罩比较 def save_screenshot_mask(self,url, output_path, elements, clip=None): locs = [] self.page.goto(url) for element in elements: loc = self.page.locator(element) locs.append(loc) self.page.screenshot(path=output_path,mask=locs, clip=clip) #网页直接截图方法,适用于网页元素不变,可直接截图比较 def save_screenshot(self,url, output_path, clip=None): self.page.goto(url) self.page.screenshot(path=output_path, clip=clip) def compare_images(self, image1_path, image2_path): image1 = Image.open(image1_path) image2 = Image.open(image2_path) diff = ImageChops.difference(image1, image2) if diff.getbbox() is None: INFO("两张图片完全相同") return True else: INFO("两张图片存在差异") return False #对比样本快照与当前快照 def contrast_snapshot(self,url,expected_screenshot,current_screenshot,clip): # 如果不存在样本照片,生成样本照片 if not os.path.exists(expected_screenshot): self.save_screenshot(url, expected_screenshot,clip) INFO(f"样本快照已保存:{expected_screenshot}") #生成对比照片 apilink.save_screenshot(url, current_screenshot,clip) INFO(f"对比快照已保存:{expected_screenshot}") #返回对比结果 result = apilink.compare_images(current_screenshot, expected_screenshot) return result #对比样本快照与当前快照2 def contrast_snapshot_mask(self,url,expected_screenshot,current_screenshot,element,clip): # 如果不存在样本照片,生成样本照片 if not os.path.exists(expected_screenshot): self.save_screenshot_mask(url, expected_screenshot,element,clip) INFO(f"样本快照已保存:{expected_screenshot}") #生成对比照片 apilink.save_screenshot_mask(url, current_screenshot,element,clip) INFO(f"对比快照已保存:{expected_screenshot}") #返回对比结果 result = apilink.compare_images(current_screenshot, expected_screenshot) return result apilink = APILink()