从公众号转载,关注微信公众号掌握更多技术动态
---------------------------------------------------------------
一、基础入门
1.简单介绍
playwright是一款新型的自动化测试工具,功能非常强大,使用下来有很多的优点
-
支持异步。
-
内置浏览器驱动。
-
支持移动端。
-
代码生成。
-
安装和使用都非常简单。
2.安装
pip install --upgrade pip
pip install playwright # 安装playwright
playwright install # 安装驱动
3.基本使用方法
(1)同步模式
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
page.goto('http://www.baidu.com')
print(page.title)
browser.close()
(2)异步模式
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=False)
page = await browser.new_page()
await page.goto("http://www.baidu.com")
print(await page.title())
await browser.close()
asyncio.run(main())
二、实际应用及踩坑事项
1.实际应用
(1)接口
@app.route("/screenShotArea", methods=["POST"])
def run():
handle_result = {"code": "200", "msg": "SUCCESS"}
try:
cmd_str = "python3 src/screenshot/screenshot.py"
os.system(cmd_str)
except Exception as e:
log.error(f"截图处理中发生异常: {str(e)}")
handle_result = {"code": "500", "msg": "系统异常"}
return handle_result
(2)执行截图文件
if __name__ == "__main__":
with sync_playwright() as p:
Screenshot().run(p)
def run(self,p):
browser = p.chromium.launch(headless=True)
context = browser.new_context(viewport=SCREENSHOT_VIEWPORT)
page = context.new_page()
# 具体截图操作
page.close()
browser.close()
2.踩坑项
(1)同步playwright在linux下只能在main方法下执行
如果想要通过接口形式调用则需要使用
cmd_str = "python3 src/screenshot/screenshot.py"
os.system(cmd_str)
但是这种方法导致文件引用关系异常,需要把引用的相关路径加到sys中
project_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # 获取当前文件的绝对路径
print(project_path)
sys.path.append(project_path)
(2)异步playwright在linux下会一直等待
(3)linux版本不匹配
playwright对系统的版本要求较高,如果出现让升级系统的提示绝对不要升级,如果升级失败可以采用以下方式进行回退
libstdc++.so.6软连接指向了一个不存在的libstdc++.so.6.0.21报错
解决方法:
只需要先删除这个软链接,之后重新设置一个软链接让libstdc++.so.6 指向我们机器上的那个版本libstdc++.so.6.0.19就解决这个问题了
3.截图验证
防止截图是未加载完成的图片,可以通过识别文字的方式验证图片是否加载完成(tesseract的使用参考网络)
def valid_screen_shot(self, image_path):
if not VALID_SCREENSHOT_SWITCH:
return True
image = cv2.imread(image_path)
# 使用Tesseract进行文字识别
text = pytesseract.image_to_string(image, lang='chi_sim')
cv2.destroyAllWindows()
# 判断识别结果是否包含中文
if re.search('[\u4e00-\u9fff]', text):
return True
return False