跳到主要内容

版本说明

版本 1.52

亮点

  • 新增方法 assertThat(locator).containsClass(),可便捷地断言元素的单个类名。

      assertThat(page.getByRole(AriaRole.LISTITEM, new Page.GetByRoleOptions().setName("Ship v1.52"))).containsClass("done");
  • Aria 快照新增了两个属性:用于严格匹配的 /children 和用于链接的 /url

    assertThat(locator).toMatchAriaSnapshot("""
    - list
    - /children: equal
    - listitem: Feature A
    - listitem:
    - link "Feature B":
    - /url: "https://playwright.net.cn"
    """);

杂项

  • APIRequest.newContext() 中新增选项 setMaxRedirects,用于控制最大重定向次数。
  • Locator.ariaSnapshot() 中新增选项 setRef,用于在快照中为每个元素生成引用,该引用后续可用于定位元素。
  • HTML 报告现在支持通过 !@my-tag!my-file.spec.ts!p:my-project 进行 *排除过滤*。

重大变更

  • Page.frame() 中不再支持 Base URL 匹配。我们建议迁移到 Page.frameLocator(),以获得更便捷的 API。
  • Page.route() 等方法中的 Glob URL 模式不再支持 ?[]。我们建议改用正则表达式。
  • 方法 Route.resume() 不再允许覆盖 Cookie 头部。如果提供了 Cookie 头部,它将被忽略,cookie 将从浏览器的 cookie 存储中加载。要设置自定义 cookie,请使用 BrowserContext.addCookies()
  • macOS 13 现已弃用,将不再接收 WebKit 更新。请升级到更新的 macOS 版本,以继续受益于最新的 WebKit 改进。

浏览器版本

  • Chromium 136.0.7103.25
  • Mozilla Firefox 137.0
  • WebKit 18.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 135
  • Microsoft Edge 135

版本 1.51

亮点

  • BrowserContext.storageState() 的新增选项 setIndexedDB 允许保存和恢复 IndexedDB 内容。当您的应用程序使用 IndexedDB API 存储身份验证令牌(如 Firebase Authentication)时非常有用。

    这是一个遵循身份验证指南的示例

    // Save storage state into the file. Make sure to include IndexedDB.
    context.storageState(new BrowserContext.StorageStateOptions()
    .setPath(Paths.get("state.json"))
    .setIndexedDB(true));

    // Create a new context with the saved storage state.
    BrowserContext context = browser.newContext(new Browser.NewContextOptions()
    .setStorageStatePath(Paths.get("state.json")));
  • Locator.filter() 的新增选项 setVisible 允许仅匹配可见元素。

    // Ignore invisible todo items.
    Locator todoItems = page.getByTestId("todo-item")
    .filter(new Locator.FilterOptions().setVisible(true));
    // Check there are exactly 3 visible ones.
    assertThat(todoItems).hasCount(3);
  • 方法 Page.emulateMedia()Browser.newContext() 的新增选项 setContrast 允许模拟 prefers-contrast 媒体特性。

  • 新增选项 setFailOnStatusCode 会使得通过 APIRequestContext 发出的所有 fetch 请求在遇到非 2xx 和 3xx 响应代码时抛出错误。

浏览器版本

  • Chromium 134.0.6998.35
  • Mozilla Firefox 135.0
  • WebKit 18.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 133
  • Microsoft Edge 133

版本 1.50

杂项

UI 更新

  • Codegen 中新增按钮,用于拾取元素以生成 aria 快照。
  • 现在在跟踪中,除了动作 API 调用外,还会显示更多详细信息(例如按键)。
  • 在跟踪中显示 canvas 内容容易出错。现在默认禁用显示,可以通过 UI 设置中的“显示 canvas 内容”选项启用。
  • “调用”和“网络”面板现在显示额外的时序信息。

重大变更

浏览器版本

  • Chromium 133.0.6943.16
  • Mozilla Firefox 134.0
  • WebKit 18.2

此版本还针对以下稳定通道进行了测试

  • Google Chrome 132
  • Microsoft Edge 132

版本 1.49

Aria 快照

新增断言 assertThat(locator).matchesAriaSnapshot(),通过与预期的可访问性树(以 YAML 表示)进行比较来验证页面结构。

page.navigate("https://playwright.net.cn");
assertThat(page.locator("body")).matchesAriaSnapshot("""
- banner:
- heading /Playwright enables reliable/ [level=1]
- link "Get started"
- link "Star microsoft/playwright on GitHub"
- main:
- img "Browsers (Chromium, Firefox, WebKit)"
- heading "Any browser • Any platform • One API"
""");

您可以使用测试生成器或调用Locator.ariaSnapshot()来生成此断言。

aria 快照指南中了解更多信息。

跟踪分组

新增方法 Tracing.group() 允许您在跟踪查看器中直观地对操作进行分组。

// All actions between group and groupEnd
// will be shown in the trace viewer as a group.
page.context().tracing().group("Open Playwright.dev > API");
page.navigate("https://playwright.net.cn/");
page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions().setName("API")).click();
page.context().tracing().groupEnd();

重大变更:chrome 和 msedge 通道切换到新的无头模式

如果您在 playwright.config.ts 中使用了以下任一通道,此更改将影响您

  • chrome, chrome-dev, chrome-beta, 或 chrome-canary
  • msedge, msedge-dev, msedge-beta, 或 msedge-canary

更新到 Playwright v1.49 后,运行您的测试套件。如果仍然通过,则无需进一步操作。如果失败,您可能需要更新快照,并调整一些关于 PDF 查看器和扩展的测试代码。更多详情请参阅问题 #33566

尝试新的 Chromium 无头模式

您可以通过使用 'chromium' 通道来选择新的无头模式。正如官方 Chrome 文档所述

另一方面,新的无头模式是真实的 Chrome 浏览器,因此更真实、更可靠,并提供更多功能。这使其更适合高精度的端到端 Web 应用程序测试或浏览器扩展测试。

有关可能遇到的潜在破坏性变更列表以及 Chromium 无头模式的更多详细信息,请参阅问题 #33566。如果在选择加入后遇到任何问题,请提交 issue。

Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setChannel("chromium"));

杂项

  • Ubuntu 20.04 和 Debian 11 上的 WebKit 将不再有更新。我们建议将您的操作系统更新到更高版本。
  • 快照内的 <canvas> 元素现在会绘制预览。

浏览器版本

  • Chromium 131.0.6778.33
  • Mozilla Firefox 132.0
  • WebKit 18.2

此版本还针对以下稳定通道进行了测试

  • Google Chrome 130
  • Microsoft Edge 130

版本 1.48

WebSocket 路由

新增方法 Page.routeWebSocket()BrowserContext.routeWebSocket() 允许拦截、修改和模拟页面中发起的 WebSocket 连接。下面是一个简单的示例,通过对名为 'request' 的消息响应名为 'response' 的消息来模拟 WebSocket 通信。

page.routeWebSocket("/ws", ws -> {
ws.onMessage(frame -> {
if ("request".equals(frame.text()))
ws.send("response");
});
});

更多详情请参阅WebSocketRoute

UI 更新

  • HTML 报告中新增了用于复制注解和测试位置的“复制”按钮。
  • Route.fulfill() 等路由方法调用不再显示在报告和跟踪查看器中。您可以在网络选项卡中查看哪些网络请求被路由。
  • 网络选项卡中新增了用于请求的“复制为 cURL”和“复制为 fetch”按钮。

杂项

  • 新增方法 Page.requestGC() 可能有助于检测内存泄漏。
  • 通过APIRequestContext 发送的请求现在会在 HAR 中记录详细的时序和安全信息。

浏览器版本

  • Chromium 130.0.6723.19
  • Mozilla Firefox 130.0
  • WebKit 18.0

此版本还针对以下稳定通道进行了测试

  • Google Chrome 129
  • Microsoft Edge 129

版本 1.47

网络选项卡改进

跟踪查看器中的网络选项卡有几项不错的改进

  • 按资产类型和 URL 过滤
  • 更好地显示查询字符串参数
  • 字体资源的预览

Network tab now has filters

杂项

  • mcr.microsoft.com/playwright/java:v1.47.0 现在提供基于 Ubuntu 24.04 Noble 的 Playwright 镜像。要使用基于 22.02 jammy 的镜像,请改用 mcr.microsoft.com/playwright/java:v1.47.0-jammy
  • Playwright Docker 镜像的 :latest/:focal/:jammy 标签不再发布。请固定到特定版本以获得更好的稳定性和可重现性。
  • 现在可以通过将 setClientCertificates.setCertsetClientCertificates.setKey 作为字节数组而不是文件路径来从内存中传递 TLS 客户端证书。
  • Locator.selectOption() 中的 setNoWaitAfter 已弃用。
  • 我们收到报告称,WebGL 在 Webkit 的 GitHub Actions macos-13 上行为异常。我们建议将 GitHub Actions 升级到 macos-14

浏览器版本

  • Chromium 129.0.6668.29
  • Mozilla Firefox 130.0
  • WebKit 18.0

此版本还针对以下稳定通道进行了测试

  • Google Chrome 128
  • Microsoft Edge 128

版本 1.46

TLS 客户端证书

Playwright 现在允许提供客户端证书,以便服务器可以根据 TLS 客户端身份验证的规范验证它们。

您可以通过 Browser.newContext()APIRequest.newContext() 的参数来提供客户端证书。以下代码片段为 https://example.com 设置客户端证书

BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setClientCertificates(asList(new ClientCertificate("https://example.com")
.setCertPath(Paths.get("client-certificates/cert.pem"))
.setKeyPath(Paths.get("client-certificates/key.pem")))));

跟踪查看器更新

  • 文本附件的内容现在在附件面板中内联渲染。
  • 新增设置用于显示/隐藏 Route.resume() 等路由操作。
  • 请求方法和状态显示在网络详情选项卡中。
  • 新增按钮用于将源文件位置复制到剪贴板。
  • 元数据面板现在显示 baseURL

杂项

浏览器版本

  • Chromium 128.0.6613.18
  • Mozilla Firefox 128.0
  • WebKit 18.0

此版本还针对以下稳定通道进行了测试

  • Google Chrome 127
  • Microsoft Edge 127

版本 1.45

时钟

利用新的Clock API,可以在测试中操作和控制时间,以验证与时间相关的行为。此 API 涵盖了许多常见场景,包括

  • 使用预定义时间进行测试;
  • 保持一致的时间和定时器;
  • 监视非活动状态;
  • 手动推进时间。
// Initialize clock with some time before the test time and let the page load
// naturally. `Date.now` will progress as the timers fire.
page.clock().install(new Clock.InstallOptions().setTime("2024-02-02T08:00:00"));
page.navigate("http://localhost:3333");
Locator locator = page.getByTestId("current-time");

// Pretend that the user closed the laptop lid and opened it again at 10am.
// Pause the time once reached that point.
page.clock().pauseAt("2024-02-02T10:00:00");

// Assert the page state.
assertThat(locator).hasText("2/2/2024, 10:00:00 AM");

// Close the laptop lid again and open it at 10:30am.
page.clock().fastForward("30:00");
assertThat(locator).hasText("2/2/2024, 10:30:00 AM");

更多详情请参阅时钟指南

杂项

  • 方法 Locator.setInputFiles() 现在支持为 <input type=file webkitdirectory> 元素上传目录。

    page.getByLabel("Upload directory").setInputFiles(Paths.get("mydir"));
  • 多个方法(如 Locator.click()Locator.press())现在支持 ControlOrMeta 修饰键。此键在 macOS 上映射到 Meta,在 Windows 和 Linux 上映射到 Control

    // Press the common keyboard shortcut Control+S or Meta+S to trigger a "Save" operation.
    page.keyboard.press("ControlOrMeta+S");
  • APIRequest.newContext() 中新增属性 httpCredentials.send,允许始终发送 Authorization 头部,或仅在响应 401 Unauthorized 时发送。

  • Playwright 现在支持在 Ubuntu 24.04 上使用 Chromium、Firefox 和 WebKit。

  • v1.45 是最后一个为 macOS 12 Monterey 提供 WebKit 更新的版本。请更新 macOS 以继续使用最新的 WebKit。

浏览器版本

  • Chromium 127.0.6533.5
  • Mozilla Firefox 127.0
  • WebKit 17.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 126
  • Microsoft Edge 126

版本 1.44

新增 API

无障碍断言

定位器处理程序

  • 执行通过 Page.addLocatorHandler() 添加的处理程序后,Playwright 现在将等待触发处理程序的覆盖层不再可见。您可以通过新的 setNoWaitAfter 选项选择退出此行为。
  • 您可以使用 Page.addLocatorHandler() 中的新 setTimes 选项来指定处理程序应该运行的最大次数。
  • Page.addLocatorHandler() 中的处理程序现在接受定位器作为参数。
  • 新增方法 Page.removeLocatorHandler(),用于移除先前添加的定位器处理程序。
Locator locator = page.getByText("This interstitial covers the button");
page.addLocatorHandler(locator, overlay -> {
overlay.locator("#close").click();
}, new Page.AddLocatorHandlerOptions().setTimes(3).setNoWaitAfter(true));
// Run your tests that can be interrupted by the overlay.
// ...
page.removeLocatorHandler(locator);

杂项选项

  • 新增方法 FormData.append() 允许在 RequestOptionssetMultipart 选项中指定具有相同名称的重复字段。

    FormData formData = FormData.create();
    formData.append("file", new FilePayload("f1.js", "text/javascript",
    "var x = 2024;".getBytes(StandardCharsets.UTF_8)));
    formData.append("file", new FilePayload("f2.txt", "text/plain",
    "hello".getBytes(StandardCharsets.UTF_8)));
    APIResponse response = context.request().post("https://example.com/uploadFile", RequestOptions.create().setMultipart(formData));
  • expect(page).toHaveURL(url) 现在支持 setIgnoreCase 选项。

浏览器版本

  • Chromium 125.0.6422.14
  • Mozilla Firefox 125.0.1
  • WebKit 17.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 124
  • Microsoft Edge 124

版本 1.43

新增 API

  • 方法 BrowserContext.clearCookies() 现在支持过滤器,以仅移除部分 cookie。

    // Clear all cookies.
    context.clearCookies();
    // New: clear cookies with a particular name.
    context.clearCookies(new BrowserContext.ClearCookiesOptions().setName("session-id"));
    // New: clear cookies for a particular domain.
    context.clearCookies(new BrowserContext.ClearCookiesOptions().setDomain("my-origin.com"));
  • 新增方法 Locator.contentFrame()Locator 对象转换为FrameLocator。这在您已获得一个Locator 对象,并希望稍后与框架内的内容进行交互时非常有用。

    Locator locator = page.locator("iframe[name='embedded']");
    // ...
    FrameLocator frameLocator = locator.contentFrame();
    frameLocator.getByRole(AriaRole.BUTTON).click();
  • 新增方法 FrameLocator.owner()FrameLocator 对象转换为Locator。这在您已获得一个FrameLocator 对象,并希望稍后与 iframe 元素进行交互时非常有用。

    FrameLocator frameLocator = page.frameLocator("iframe[name='embedded']");
    // ...
    Locator locator = frameLocator.owner();
    assertThat(locator).isVisible();

浏览器版本

  • Chromium 124.0.6367.8
  • Mozilla Firefox 124.0
  • WebKit 17.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 123
  • Microsoft Edge 123

版本 1.42

实验性 JUnit 集成

在您的测试类中添加新的 @UsePlaywright 注解,以便在测试方法中开始使用 Page、BrowserContext、Browser、APIRequestContext 和 Playwright 的 Playwright fixture。

package org.example;

import com.microsoft.playwright.Page;
import com.microsoft.playwright.junit.UsePlaywright;
import org.junit.jupiter.api.Test;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;

@UsePlaywright
public class TestExample {
void shouldNavigateToInstallationGuide(Page page) {
page.navigate("https://playwright.net.cn/java/");
page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions().setName("Docs")).click();
assertThat(page.getByRole(AriaRole.HEADING, new Page.GetByRoleOptions().setName("Installation"))).isVisible();
}

@Test
void shouldCheckTheBox(Page page) {
page.setContent("<input id='checkbox' type='checkbox'></input>");
page.locator("input").check();
assertEquals(true, page.evaluate("window['checkbox'].checked"));
}

@Test
void shouldSearchWiki(Page page) {
page.navigate("https://www.wikipedia.org/");
page.locator("input[name=\"search\"]").click();
page.locator("input[name=\"search\"]").fill("playwright");
page.locator("input[name=\"search\"]").press("Enter");
assertThat(page).hasURL("https://en.wikipedia.org/wiki/Playwright");
}
}

在上面的示例中,所有三个测试方法使用同一个Browser。每个测试使用自己的BrowserContextPage

自定义选项

实现您自己的 OptionsFactory,以便使用自定义配置初始化 fixture。

import com.microsoft.playwright.junit.Options;
import com.microsoft.playwright.junit.OptionsFactory;
import com.microsoft.playwright.junit.UsePlaywright;

@UsePlaywright(MyTest.CustomOptions.class)
public class MyTest {

public static class CustomOptions implements OptionsFactory {
@Override
public Options getOptions() {
return new Options()
.setHeadless(false)
.setContextOption(new Browser.NewContextOptions()
.setBaseURL("https://github.com"))
.setApiRequestOptions(new APIRequest.NewContextOptions()
.setBaseURL("https://playwright.net.cn"));
}
}

@Test
public void testWithCustomOptions(Page page, APIRequestContext request) {
page.navigate("/");
assertThat(page).hasURL(Pattern.compile("github"));

APIResponse response = request.get("/");
assertTrue(response.text().contains("Playwright"));
}
}

在我们的JUnit 指南中了解更多关于 fixture 的信息。

新增定位器处理程序

新增方法 Page.addLocatorHandler() 注册一个回调,当指定的元素变为可见并可能阻止 Playwright 操作时,该回调将被调用。该回调可以移除覆盖层。下面是一个当 cookie 对话框出现时将其关闭的示例。

// Setup the handler.
page.addLocatorHandler(
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Hej! You are in control of your cookies.")),
() -> {
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Accept all")).click();
});
// Write the test as usual.
page.navigate("https://www.ikea.com/");
page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions().setName("Collection of blue and white")).click();
assertThat(page.getByRole(AriaRole.HEADING, new Page.GetByRoleOptions().setName("Light and easy"))).isVisible();

新增 API

公告

  • ⚠️ 不再支持 Ubuntu 18。

浏览器版本

  • Chromium 123.0.6312.4
  • Mozilla Firefox 123.0
  • WebKit 17.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 122
  • Microsoft Edge 123

版本 1.41

新增 API

浏览器版本

  • Chromium 121.0.6167.57
  • Mozilla Firefox 121.0
  • WebKit 17.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 120
  • Microsoft Edge 120

版本 1.40

测试生成器更新

Playwright Test Generator

生成断言的新工具

这是一个生成带断言测试的示例

page.navigate("https://playwright.net.cn/");
page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions().setName("Get started")).click();
assertThat(page.getByLabel("Breadcrumbs").getByRole(AriaRole.LIST)).containsText("Installation");
assertThat(page.getByLabel("Search")).isVisible();
page.getByLabel("Search").click();
page.getByPlaceholder("Search docs").fill("locator");
assertThat(page.getByPlaceholder("Search docs")).hasValue("locator");

新增 API

其他变更

浏览器版本

  • Chromium 120.0.6099.28
  • Mozilla Firefox 119.0
  • WebKit 17.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 119
  • Microsoft Edge 119

版本 1.39

常青浏览器更新。

浏览器版本

  • Chromium 119.0.6045.9
  • Mozilla Firefox 118.0.1
  • WebKit 17.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 118
  • Microsoft Edge 118

版本 1.38

跟踪查看器更新

Playwright Trace Viewer

  1. 缩放时间范围。
  2. 网络面板重新设计。

新增 API

弃用

浏览器版本

  • Chromium 117.0.5938.62
  • Mozilla Firefox 117.0
  • WebKit 17.0

此版本还针对以下稳定通道进行了测试

  • Google Chrome 116
  • Microsoft Edge 116

版本 1.37

新增 API

  • 新增方法 BrowserContext.newCDPSession()Browser.newBrowserCDPSession() 分别为页面和浏览器创建 Chrome DevTools Protocol 会话。

    CDPSession cdpSession = page.context().newCDPSession(page);
    cdpSession.send("Runtime.enable");

    JsonObject params = new JsonObject();
    params.addProperty("expression", "window.foo = 'bar'");
    cdpSession.send("Runtime.evaluate", params);

    Object foo = page.evaluate("window['foo']");
    assertEquals("bar", foo);

📚 支持 Debian 12 Bookworm

Playwright 现在在 x86_64 和 arm64 架构上都支持 Debian 12 Bookworm 的 Chromium, Firefox 和 WebKit。如果您遇到任何问题,请告知我们!

Linux 支持情况如下

Ubuntu 20.04Ubuntu 22.04Debian 11Debian 12
Chromium
WebKit
Firefox

浏览器版本

  • Chromium 116.0.5845.82
  • Mozilla Firefox 115.0
  • WebKit 17.0

此版本还针对以下稳定通道进行了测试

  • Google Chrome 115
  • Microsoft Edge 115

版本 1.36

🏝️ 夏季维护版本。

浏览器版本

  • Chromium 115.0.5790.75
  • Mozilla Firefox 115.0
  • WebKit 17.0

此版本还针对以下稳定通道进行了测试

  • Google Chrome 114
  • Microsoft Edge 114

版本 1.35

亮点

  • 方法 Page.screenshot()Locator.screenshot() 新增选项 maskColor,用于更改默认遮罩颜色。

  • 新增 uninstall CLI 命令,用于卸载浏览器二进制文件

    $ mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="uninstall" # remove browsers installed by this installation
    $ mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="uninstall --all" # remove all ever-install Playwright browsers

浏览器版本

  • Chromium 115.0.5790.13
  • Mozilla Firefox 113.0
  • WebKit 16.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 114
  • Microsoft Edge 114

版本 1.34

亮点

浏览器版本

  • Chromium 114.0.5735.26
  • Mozilla Firefox 113.0
  • WebKit 16.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 113
  • Microsoft Edge 113

版本 1.33

定位器更新

  • 使用 Locator.or() 创建一个匹配两个定位器中任意一个的定位器。考虑这样一个场景:您想点击“新建电子邮件”按钮,但有时会弹出一个安全设置对话框。在这种情况下,您可以等待“新建电子邮件”按钮或对话框,并据此采取行动。

    Locator newEmail = page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("New email"));
    Locator dialog = page.getByText("Confirm security settings");
    assertThat(newEmail.or(dialog)).isVisible();
    if (dialog.isVisible())
    page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Dismiss")).click();
    newEmail.click();
  • Locator.filter() 中使用新选项 setHasNotsetHasNotText 来查找 *不* 匹配某些条件的元素。

    Locator rowLocator = page.locator("tr");
    rowLocator
    .filter(new Locator.FilterOptions().setHasNotText("text in column 1"))
    .filter(new Locator.FilterOptions().setHasNot(
    page.getByRole(AriaRole.BUTTON,
    new Page.GetByRoleOptions().setName("column 2 button" ))))
    .screenshot();
  • 使用新的 web-first 断言 assertThat(locator).isAttached() 来确保元素存在于页面的 DOM 中。请勿与 assertThat(locator).isVisible() 混淆,后者确保元素既附加又可见。

新增 API

其他亮点

  • 原生支持 Apple Silicon - Playwright 现在无需 Rosetta 即可运行
  • 添加了 Ubuntu 22.04 (Jammy) Docker 镜像

⚠️ 重大变更

  • mcr.microsoft.com/playwright/java:v1.33.0 现在提供基于 Ubuntu Jammy 的 Playwright 镜像。要使用基于 focal 的镜像,请改用 mcr.microsoft.com/playwright/java:v1.33.0-focal

浏览器版本

  • Chromium 113.0.5672.53
  • Mozilla Firefox 112.0
  • WebKit 16.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 112
  • Microsoft Edge 112

版本 1.32

新 API

浏览器版本

  • Chromium 112.0.5615.29
  • Mozilla Firefox 111.0
  • WebKit 16.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 111
  • Microsoft Edge 111

版本 1.31

新 API

  • 新增断言 assertThat(locator).isInViewport() 确保定位符指向的元素根据 Intersection Observer API 位于视口内。

    Locator locator = page.getByRole(AriaRole.BUTTON);

    // Make sure at least some part of element intersects viewport.
    assertThat(locator).isInViewport();

    // Make sure element is fully outside of viewport.
    assertThat(locator).not().isInViewport();

    // Make sure that at least half of the element intersects viewport.
    assertThat(locator).isInViewport(new LocatorAssertions.IsInViewportOptions().setRatio(0.5));

杂项

  • 跟踪查看器中的 DOM 快照现在可以在单独的窗口中打开。
  • Route.fetch() 方法新增 setMaxRedirects 选项。
  • Playwright 现在支持 Debian 11 arm64。
  • 官方 docker 镜像现在包含 Node 18 而非 Node 16。

浏览器版本

  • Chromium 111.0.5563.19
  • Mozilla Firefox 109.0
  • WebKit 16.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 110
  • Microsoft Edge 110

版本 1.30

浏览器版本

  • Chromium 110.0.5481.38
  • Mozilla Firefox 108.0.2
  • WebKit 16.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 109
  • Microsoft Edge 109

版本 1.29

新 API

  • 新增方法 Route.fetch()

    page.route("**/api/settings", route -> {
    // Fetch original settings.
    APIResponse response = route.fetch();
    // Force settings theme to a predefined value.
    String body = response.text().replace("\"theme\":\"default\"",
    "\"theme\":\"Solorized\"");
    // Fulfill with modified data.
    route.fulfill(new Route.FulfillOptions().setResponse(response).setBody(body));
    });
  • 新增方法 Locator.all() 用于遍历所有匹配的元素

    // Check all checkboxes!
    Locator checkboxes = page.getByRole(AriaRole.CHECKBOX);
    for (Locator checkbox : checkboxes.all())
    checkbox.check();
  • Locator.selectOption() 现在按值或标签匹配

    <select multiple>
    <option value="red">Red</option>
    <option value="green">Green</option>
    <option value="blue">Blue</option>
    </select>
    element.selectOption("Red");

浏览器版本

  • Chromium 109.0.5414.46
  • Mozilla Firefox 107.0
  • WebKit 16.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 108
  • Microsoft Edge 108

版本 1.28

Playwright 工具

  • CodeGen 中的实时定位符。使用“探索”工具为页面上的任何元素生成定位符。

Locator Explorer

新 API

浏览器版本

  • Chromium 108.0.5359.29
  • Mozilla Firefox 106.0
  • WebKit 16.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 107
  • Microsoft Edge 107

版本 1.27

定位符

有了这些新 API,编写定位符变得轻松愉快

page.getByLabel("User Name").fill("John");

page.getByLabel("Password").fill("secret-password");

page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign in")).click();

assertThat(page.getByText("Welcome, John!")).isVisible();

所有这些方法也适用于 LocatorFrameLocatorFrame 类。

其他亮点

  • 正如 v1.25 中宣布的,Ubuntu 18 将不再受到支持,自 2022 年 12 月起生效。除此之外,从 Playwright 的下个版本开始,将不再为 Ubuntu 18 提供 WebKit 更新。

行为变更

  • assertThat(locator).hasAttribute() 带有空值不再匹配缺少的属性。例如,当 button 没有 disabled 属性时,以下代码片段将成功执行。

    assertThat(page.getByRole(AriaRole.BUTTON)).hasAttribute("disabled", "");

浏览器版本

  • Chromium 107.0.5304.18
  • Mozilla Firefox 105.0.1
  • WebKit 16.0

此版本还针对以下稳定通道进行了测试

  • Google Chrome 106
  • Microsoft Edge 106

版本 1.26

断言

其他亮点

  • APIRequestContext.get() 等方法的新选项 setMaxRedirects,用于限制重定向次数。
  • Docker 镜像现在使用 OpenJDK 17。

行为变更

许多 Playwright API 已经支持 setWaitUntil(WaitUntilState.DOMCONTENTLOADED) 选项。例如

page.navigate("https://playwright.net.cn", new Page.NavigateOptions().setWaitUntil(WaitUntilState.DOMCONTENTLOADED));

在 1.26 之前,这将等待所有 iframe 触发 DOMContentLoaded 事件。

为了与 Web 规范保持一致,WaitUntilState.DOMCONTENTLOADED 值仅等待目标帧触发 'DOMContentLoaded' 事件。使用 setWaitUntil(WaitUntilState.LOAD) 来等待所有 iframe。

浏览器版本

  • Chromium 106.0.5249.30
  • Mozilla Firefox 104.0
  • WebKit 16.0

此版本还针对以下稳定通道进行了测试

  • Google Chrome 105
  • Microsoft Edge 105

版本 1.25

新 API 和变更

公告

  • 🪦 这是支持 macOS 10.15 的最后一个版本(自 1.21 起已弃用)。
  • ⚠️ Ubuntu 18 现已弃用,自 2022 年 12 月起不再支持。

浏览器版本

  • Chromium 105.0.5195.19
  • Mozilla Firefox 103.0
  • WebKit 16.0

此版本还针对以下稳定通道进行了测试

  • Google Chrome 104
  • Microsoft Edge 104

版本 1.24

🐂 支持 Debian 11 Bullseye

Playwright 现在在 x86_64 架构上支持 Debian 11 Bullseye,适用于 Chromium、Firefox 和 WebKit。如果您遇到任何问题,请告知我们!

Linux 支持情况如下

| | Ubuntu 20.04 | Ubuntu 22.04 | Debian 11 | :--- | :---: | :---: | :---: | :---: | | Chromium | ✅ | ✅ | ✅ | | WebKit | ✅ | ✅ | ✅ | | Firefox | ✅ | ✅ | ✅ |

版本 1.23

网络重放

现在您可以将网络流量录制到 HAR 文件中,并在测试中重复使用这些流量。

将网络录制到 HAR 文件

mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="open --save-har=example.har --save-har-glob='**/api/**' https://example.com"

或者,您可以以编程方式录制 HAR

BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setRecordHarPath(Paths.get("example.har"))
.setRecordHarUrlFilter("**/api/**"));

// ... Perform actions ...

// Close context to ensure HAR is saved to disk.
context.close();

使用新方法 Page.routeFromHAR()BrowserContext.routeFromHAR()HAR 文件提供匹配的响应。

context.routeFromHAR(Paths.get("example.har"));

详情请参阅 我们的文档

高级路由

现在您可以使用 Route.fallback() 将路由委托给其他处理程序。

考虑以下示例

// Remove a header from all requests.
page.route("**/*", route -> {
Map<String, String> headers = new HashMap<>(route.request().headers());
headers.remove("X-Secret");
route.resume(new Route.ResumeOptions().setHeaders(headers));
});

// Abort all images.
page.route("**/*", route -> {
if ("image".equals(route.request().resourceType()))
route.abort();
else
route.fallback();
});

请注意,新方法 Page.routeFromHAR()BrowserContext.routeFromHAR() 也参与路由,并且可以被委托。

Web-First 断言更新

杂项

  • 如果您的服务工作线程挡路,您现在可以使用新的上下文选项 serviceWorkers 轻松禁用它

    BrowserContext context = browser.newContext(new Browser.NewContextOptions()
    .setServiceWorkers(ServiceWorkerPolicy.BLOCK));
  • recordHar 上下文选项使用 .zip 路径会自动压缩生成的 HAR

    BrowserContext context = browser.newContext(new Browser.NewContextOptions()
    .setRecordHarPath(Paths.get("example.har.zip")));
  • 如果您打算手动编辑 HAR,请考虑使用 "minimal" HAR 录制模式,该模式仅录制重放必需的信息

    BrowserContext context = browser.newContext(new Browser.NewContextOptions()
    .setRecordHarPath(Paths.get("example.har"))
    .setRecordHarMode(HarMode.MINIMAL));
  • Playwright 现在可以在 Ubuntu 22 amd64 和 Ubuntu 22 arm64 上运行。

版本 1.22

亮点

  • 角色选择器允许通过 ARIA roleARIA attributesaccessible name 选择元素。

    // Click a button with accessible name "log in"
    page.locator("role=button[name='log in']").click();

    详情请参阅 我们的文档

  • 新增 Locator.filter() API 用于过滤现有定位符

    Locator buttonsLocator = page.locator("role=button");
    // ...
    Locator submitButton = buttonsLocator.filter(new Locator.FilterOptions().setHasText("Submit"));
    submitButton.click();
  • Playwright for Java 现在支持 Ubuntu 20.04 ARM64Apple M1。您现在可以在 Apple M1 上、Apple M1 上的 Docker 中以及 Raspberry Pi 上运行 Playwright for Java 测试。

版本 1.21

亮点

  • 新的角色选择器允许通过 ARIA roleARIA attributesaccessible name 选择元素。

    // Click a button with accessible name "log in"
    page.locator("role=button[name='log in']").click();

    详情请参阅 我们的文档

  • Page.screenshot() 中新增 scale 选项,用于生成尺寸更小的屏幕截图。

  • Page.screenshot() 中新增 caret 选项,用于控制文本插入符。默认为 "hide"

行为变更

浏览器版本

  • Chromium 101.0.4951.26
  • Mozilla Firefox 98.0.2
  • WebKit 15.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 100
  • Microsoft Edge 100

版本 1.20

亮点

公告

  • v1.20 是 macOS 10.15 Catalina 获得 WebKit 更新的最后一个版本。请更新 macOS 以继续使用最新最好的 WebKit!

浏览器版本

  • Chromium 101.0.4921.0
  • Mozilla Firefox 97.0.1
  • WebKit 15.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 99
  • Microsoft Edge 99

版本 1.19

亮点

  • Locator 现在支持 has 选项,确保它包含另一个内部定位符

    page.locator("article", new Page.LocatorOptions().setHas(page.locator(".highlight"))).click();

    详情请参阅 定位符文档

  • 新增 Locator.page()

  • Page.screenshot()Locator.screenshot() 现在自动隐藏闪烁的插入符

  • Playwright Codegen 现在生成定位符和帧定位符

浏览器版本

  • Chromium 100.0.4863.0
  • Mozilla Firefox 96.0.1
  • WebKit 15.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 98
  • Microsoft Edge 98

版本 1.18

API 测试

Playwright for Java 1.18 引入了新的 API Testing 功能,允许您直接从 Java 向服务器发送请求!现在您可以

  • 测试您的服务器 API
  • 在测试中访问 Web 应用程序之前准备服务器端状态
  • 在浏览器中运行某些操作后验证服务器端后置条件

代表 Playwright 的 Page 发送请求,使用 新的 Page.request() API

// Do a GET request on behalf of page
APIResponse res = page.request().get("http://example.com/foo.json");

详情请参阅我们的 API 测试指南

Web-First 断言

Playwright for Java 1.18 引入了 Web-First Assertions

考虑以下示例

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

public class TestExample {
@Test
void statusBecomesSubmitted() {
// ...
page.locator("#submit-button").click();
assertThat(page.locator(".status")).hasText("Submitted");
}
}

Playwright 将持续重试选择器 .status 的节点,直到获取到的节点包含文本“Submitted”。它将反复获取节点并检查它,直到满足条件或达到超时。您可以将此超时作为选项传递。

详情请参阅 我们的文档

定位符改进

  • Locator.dragTo()

  • 每个定位符现在都可以选择按其包含的文本进行过滤

    page.locator("li", new Page.LocatorOptions().setHasText("my item"))
    .locator("button").click();

    详情请参阅 定位符文档

跟踪改进

Tracing 现在可以使用新选项 setSources 将 Java 源代码嵌入到录制的跟踪文件中。

tracing-java-sources

新 API 和变更

浏览器版本

  • Chromium 99.0.4812.0
  • Mozilla Firefox 95.0
  • WebKit 15.4

此版本还针对以下稳定通道进行了测试

  • Google Chrome 97
  • Microsoft Edge 97

版本 1.17

帧定位符

Playwright 1.17 引入了 frame locators(帧定位符) - 页面上 iframe 的定位符。帧定位符捕获了检索 iframe 并随后在该 iframe 中定位元素的足够逻辑。帧定位符默认为严格模式,将等待 iframe 出现,并可在 Web-First 断言中使用。

Graphics

帧定位符可以使用 Page.frameLocator()Locator.frameLocator() 方法创建。

Locator locator = page.frameLocator("#my-frame").locator("text=Submit");
locator.click();

详情请参阅 我们的文档

跟踪查看器更新

Playwright Trace Viewer 现在已在线可用,访问 https://trace.playwright.dev!只需将 trace.zip 文件拖放到跟踪查看器 PWA 即可查看其内容。

注意:跟踪文件不会上传到任何地方;trace.playwright.dev 是一个 渐进式 Web 应用,它在本地处理跟踪文件。

  • Playwright Test 跟踪文件现在默认包含源代码(可通过 tracing 选项关闭)
  • 跟踪查看器现在显示测试名称
  • 新增跟踪元数据选项卡,包含浏览器详细信息
  • 快照现在带有 URL 地址栏

image

HTML 报告更新

  • HTML 报告现在支持动态过滤
  • 报告现在是一个静态 HTML 文件,可以通过电子邮件或作为 Slack 附件发送。

image

支持 Ubuntu ARM64 + 更多

  • Playwright 现在支持 Ubuntu 20.04 ARM64。您现在可以在 Apple M1 上的 Docker 中和 Raspberry Pi 上运行 Playwright 测试。

  • 您现在可以使用 Playwright 在 Linux 上安装 Edge 的稳定版本

    mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install msedge"

新 API

  • Tracing 现在支持一个 'title' 选项
  • 页面导航支持一个新的 'commit' 等待选项

版本 1.16

🎭 Playwright 库

Locator.waitFor

等待定位符解析为具有给定状态的单个元素。默认为 state: 'visible'

Locator orderSent = page.locator("#order-sent");
orderSent.waitFor();

阅读更多关于 Locator.waitFor() 的内容。

🎭 Playwright 跟踪查看器

  • 使用 mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="show-trace" 运行跟踪查看器,并将跟踪文件拖放到跟踪查看器 PWA 中
  • 更好的动作目标的视觉归属

阅读更多关于 Trace Viewer 的内容。

浏览器版本

  • Chromium 97.0.4666.0
  • Mozilla Firefox 93.0
  • WebKit 15.4

此版本 Playwright 也已通过以下稳定渠道测试

  • Google Chrome 94
  • Microsoft Edge 94

版本 1.15

🖱️ 鼠标滚轮

通过使用 Mouse.wheel(),您现在可以垂直或水平滚动。

📜 新 Headers API

以前无法获取响应的多个头值。现在可以了,并且提供了额外的辅助函数

🌈 Forced-Colors 模拟

现在可以通过在 Browser.newContext() 中传递或调用 Page.emulateMedia() 来模拟 forced-colors CSS 媒体特性。

新 API

浏览器版本

  • Chromium 96.0.4641.0
  • Mozilla Firefox 92.0
  • WebKit 15.0

版本 1.14

⚡️ 新“严格”模式

选择器歧义是自动化测试中的常见问题。“严格”模式确保您的选择器指向单个元素,否则会抛出错误。

在您的动作调用中设置 setStrict(true) 以选择加入。

// This will throw if you have more than one button!
page.click("button", new Page.ClickOptions().setStrict(true));

📍 新 Locators API

Locator 代表页面上元素(们)的视图。它捕获了在任何给定时刻检索元素的足够逻辑。

Locator 和 ElementHandle 之间的区别在于,后者指向一个特定的元素,而 Locator 捕获了如何检索该元素的逻辑。

此外,定位符默认是“严格”的

Locator locator = page.locator("button");
locator.click();

文档中了解更多信息。

🧩 实验性 ReactVue 选择器引擎

React 和 Vue 选择器允许按其组件名称和/或属性值选择元素。语法与 属性选择器 非常相似,并支持所有属性选择器运算符。

page.locator("_react=SubmitButton[enabled=true]").click();
page.locator("_vue=submit-button[enabled=true]").click();

react 选择器文档vue 选择器文档 中了解更多信息。

✨ 新 nthvisible 选择器引擎

  • nth 选择器引擎等同于 :nth-match 伪类,但可以与其它选择器引擎组合使用。
  • visible 选择器引擎等同于 :visible 伪类,但可以与其它选择器引擎组合使用。
// select the first button among all buttons
button.click("button >> nth=0");
// or if you are using locators, you can use first(), nth() and last()
page.locator("button").first().click();

// click a visible button
button.click("button >> visible=true");

浏览器版本

  • Chromium 94.0.4595.0
  • Mozilla Firefox 91.0
  • WebKit 15.0

版本 1.13

Playwright

工具

  • Playwright Trace Viewer 现在显示参数、返回值和 console.log() 调用。

新增和重写的指南

浏览器版本

  • Chromium 93.0.4576.0
  • Mozilla Firefox 90.0
  • WebKit 14.2

新的 Playwright API

版本 1.12

🧟‍♂️ 介绍 Playwright Trace Viewer

Playwright Trace Viewer 是一种新的 GUI 工具,有助于在脚本运行后浏览录制的 Playwright traces。Playwright traces 允许您检查

  • 每个 Playwright action 之前和之后的页面 DOM
  • 每个 Playwright action 之前和之后的页面渲染
  • 脚本执行期间的浏览器网络

使用新的 BrowserContext.tracing() API 录制 Traces

Browser browser = playwright.chromium().launch();
BrowserContext context = browser.newContext();

// Start tracing before creating / navigating a page.
context.tracing().start(new Tracing.StartOptions()
.setScreenshots(true)
.setSnapshots(true));

Page page = context.newPage();
page.navigate("https://playwright.net.cn");

// Stop tracing and export it into a zip archive.
context.tracing().stop(new Tracing.StopOptions()
.setPath(Paths.get("trace.zip")));

稍后使用 Playwright CLI 查看 Traces

mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="show-trace trace.zip"

这将打开以下 GUI

image

👉 了解更多信息,请参阅trace viewer 文档

浏览器版本

  • Chromium 93.0.4530.0
  • Mozilla Firefox 89.0
  • WebKit 14.2

此版本 Playwright 也已通过以下稳定渠道测试

  • Google Chrome 91
  • Microsoft Edge 91

新 API

版本 1.11

🎥 新视频:Playwright: A New Test Automation Framework for the Modern Web (幻灯片)

  • 我们谈论了 Playwright
  • 展示了幕后的工程工作
  • 展示了新功能的现场演示 ✨
  • 特别感谢 applitools 主办活动并邀请我们!

浏览器版本

  • Chromium 92.0.4498.0
  • Mozilla Firefox 89.0b6
  • WebKit 14.2

新 API

版本 1.10

捆绑的浏览器版本

  • Chromium 90.0.4430.0
  • Mozilla Firefox 87.0b10
  • WebKit 14.2

此版本 Playwright 也已通过以下稳定渠道测试

  • Google Chrome 89
  • Microsoft Edge 89

新 API

版本 1.9

  • Playwright Inspector 是用于编写和调试测试的新 GUI 工具
    • 逐行调试 Playwright 脚本,支持播放、暂停和单步执行。
    • 通过录制用户操作编写新脚本。
    • 通过悬停在元素上为脚本生成元素选择器。
    • 设置 PWDEBUG=1 环境变量以启动 Inspector
  • 在有头模式下,使用 Page.pause() 暂停脚本执行。暂停页面将启动 Playwright Inspector 进行调试。
  • CSS 选择器的新 has-text 伪类:has-text("example") 匹配包含 "example" 在内部某处(可能在其子元素或后代元素中)的任何元素。查看更多示例
  • 除非配置了 dialog 事件的监听器,否则页面对话框在执行期间会自动关闭了解更多
  • Playwright for Python 现已稳定,提供惯用的 snake case API 和预构建的 Docker image 用于在 CI/CD 中运行测试。

浏览器版本

  • Chromium 90.0.4421.0
  • Mozilla Firefox 86.0b10
  • WebKit 14.1

新 API

版本 1.8

新 API

浏览器版本

  • Chromium 90.0.4392.0
  • Mozilla Firefox 85.0b5
  • WebKit 14.1

版本 1.7

  • 新的 Java SDKPlaywright for Java 现在与 JavaScriptPython.NET 绑定保持一致。
  • 浏览器存储 API:新增便捷 API 用于保存和加载浏览器存储状态(cookies、local storage),以简化带认证的自动化场景。
  • 新 CSS 选择器:我们听取了关于更灵活选择器的反馈,并改进了选择器实现。Playwright 1.7 引入了新的 CSS 扩展,更多内容即将推出。
  • 新网站:位于 playwright.dev 的文档网站已更新,现在使用 Docusaurus 构建。
  • 支持 Apple Silicon:Playwright 针对 WebKit 和 Chromium 的浏览器二进制文件现在为 Apple Silicon 构建。

新 API

浏览器版本

  • Chromium 89.0.4344.0
  • Mozilla Firefox 84.0b9
  • WebKit 14.1