Playwright 使用心得

310 字
2 分钟
Playwright 使用心得
  1. 尽量不要使用 sleep 实现等待,改为使用 page.waitForTimeout 方式,原因是 sleep 有可能导致 playwright 相关的监听事件无法触发,例如 page.onResponse 有可能不正常触发
  2. LoadState 的区别
public enum LoadState {
LOAD, // The load state indicates that the entire page, including all dependent resources such as images, stylesheets, scripts, and other resources, has finished loading. This state is useful when you want to ensure that all content is fully available before interacting with the page. However, this doesn’t track the ongoing network requests. When the load event is fired, there can still be ongoing network requests in the backend.
DOMCONTENTLOADED, // The domcontentloaded state indicates that the DOMContentLoaded event has fired, meaning the HTML document has been completely loaded and parsed. However, that doesn’t mean that all stylesheets and resources are loaded. This can be considered as the initial page load.
NETWORKIDLE // Network idle state indicates that there is no ongoing network request of at least 500 milliseconds. This state is beneficial for applications that make multiple asynchronous requests, as it ensures that all network activity has been completed before proceeding. This state is mostly useful in single-page applications.
}
  1. 通过 page.route 可以拦截修改返回结果
page.route("**/waybillRoute/skipVerify*", route -> {
try {
APIResponse originalResponse = route.fetch();
String body = originalResponse.text();
// {"traceId":"08b30764b981490da450fd39fc1529a9","timestamp":"2025-08-01
// 13:22:25.449","success":true,"code":0,"message":"请求成功","detailMessage":null,"result":"0","obj":null}
JsonNode jsonNode = JsonUtils.parseJSONObject(body);
if (!jsonNode.get("result").asBoolean()) {
ObjectNode objectNode = (ObjectNode)jsonNode;
objectNode.put("result", true);
body = JsonUtils.toJsonStr(jsonNode);
log.info("自动登录失败,返回结果: {}, 修改后结果: {}", originalResponse.text(), body);
}
route.fulfill(new Route.FulfillOptions().setBody(body).setHeaders(originalResponse.headers()));
} catch (Exception e) {
route.resume();
}
});

参考资料#

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

Playwright 使用心得
https://blog.sephy.top/posts/playwright-使用心得/
作者
虾米
发布于
2025-08-08
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author
虾米
coder
分类
标签
站点统计
文章
61
分类
4
标签
52
总字数
64,663
运行时长
0
最后活动
0 天前
站点信息
构建平台
GitHub Actions
博客版本
Firefly v6.13.9
文章许可
CC BY-NC-SA 4.0