Playwright 是由微软的研发团队所开发的一款 Web 自动化测试框架,这个框架具有多平台、跨语言的特点。除了基本的自动化测试能力之外,同时它还具备非常强大的录制功能、追踪功能。以下是 Playwright 与 Selenium 的对比。
由此可见,Playwright 不仅具备 Selenium 多语言、跨平台、多浏览器的优点。相较于 Selenium,Playwright 还有更加强大的优势。
Playwright 有哪些优点
-
支持所有流行的浏览器。
-
速度更快,更可靠的执行。
-
更强大的自动化测试配置。
-
强大的工具库:
-
Codegen:通过记录你的操作来生成测试。 将它们保存为任何语言。
-
Playwright inspector: 检查页面、生成选择器、逐步执行测试、查看点击点、探索执行日志。
-
Trace Viewer:捕获所有信息以调查测试失败,Playwright 跟踪包含测试执行截屏、实时 DOM 快照、动作资源管理器、测试源等等。
-
环境安装
Python 版本
-
安装 playwright 插件:
pip install pytest-playwright
-
安装所需的浏览器:
playwright install
Java 版本
-
在 pom.xml 中添加依赖。
<!-- playwright依赖 -->
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.29.0</version>
</dependency>
<!-- maven编译使用的插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
</plugin>
-
创建一个项目
import com.microsoft.playwright.*;
import java.nio.file.Paths;
public class App {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.webkit().launch();
Page page = browser.newPage();
page.navigate("http://whatsmyuseragent.org/");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("example.png")));
}
}
}
-
编译并执行(注意:第一次编译执行的时候需要下载对应的依赖,耗时比较久。)
mvn compile exec:java -Dexec.mainClass="包名.文件名"
Codegen 录制功能
Codegen 在启动录制的时候,可以针对于不同的场景,设定不同的参