跳至主要内容

Network

简介

Playwright 提供了API来监控修改浏览器网络流量,包括HTTP和HTTPS。页面发出的任何请求,包括XHRsfetch请求,都可以被跟踪、修改和处理。

模拟API接口

查看我们的API模拟指南了解更多关于如何

  • 模拟API请求而无需实际调用API
  • 执行API请求并修改响应
  • 使用HAR文件来模拟网络请求。

网络模拟

您无需进行任何配置即可模拟网络请求。只需定义一个自定义的Route来为浏览器上下文模拟网络即可。

example.spec.ts
import { test, expect } from '@playwright/test';

test.beforeEach(async ({ context }) => {
// Block any css requests for each test in this file.
await context.route(/.css$/, route => route.abort());
});

test('loads page without css', async ({ page }) => {
await page.goto('https://playwright.dev');
// ... test goes here
});

或者,您可以使用page.route()来模拟单个页面中的网络请求。

example.spec.ts
import { test, expect } from '@playwright/test';

test('loads page without images', async ({ page }) => {
// Block png and jpeg images.
await page.route(/(png|jpeg)$/, route => route.abort());

await page.goto('https://playwright.dev');
// ... test goes here
});

HTTP认证

执行HTTP认证。

playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
httpCredentials: {
username: 'bill',
password: 'pa55w0rd',
}
}
});

HTTP代理

您可以配置页面通过HTTP(S)代理或SOCKSv5加载。代理可以全局设置用于整个浏览器,也可以单独为每个浏览器上下文设置。

您可以选择性地为HTTP(S)代理指定用户名和密码,也可以指定要绕过proxy的主机。

这是一个全局代理的示例:

playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
proxy: {
server: 'http://myproxy.com:3128',
username: 'usr',
password: 'pwd'
}
}
});

也可以针对每个上下文单独指定:

example.spec.ts
import { test, expect } from '@playwright/test';

test('should use custom proxy on a new context', async ({ browser }) => {
const context = await browser.newContext({
proxy: {
server: 'http://myproxy.com:3128',
}
});
const page = await context.newPage();

await context.close();
});

网络事件

您可以监控所有的Request请求和Response响应:

// Subscribe to 'request' and 'response' events.
page.on('request', request => console.log('>>', request.method(), request.url()));
page.on('response', response => console.log('<<', response.status(), response.url()));

await page.goto('https://example.com');

或者点击按钮后使用page.waitForResponse()等待网络响应:

// Use a glob URL pattern. Note no await.
const responsePromise = page.waitForResponse('**/api/fetch_data');
await page.getByText('Update').click();
const response = await responsePromise;

变体

等待Response响应,使用page.waitForResponse()

// Use a RegExp. Note no await.
const responsePromise = page.waitForResponse(/\.jpeg$/);
await page.getByText('Update').click();
const response = await responsePromise;

// Use a predicate taking a Response object. Note no await.
const responsePromise = page.waitForResponse(response => response.url().includes(token));
await page.getByText('Update').click();
const response = await responsePromise;

处理请求

await page.route('**/api/fetch_data', route => route.fulfill({
status: 200,
body: testData,
}));
await page.goto('https://example.com');

你可以通过在Playwright脚本中处理网络请求来模拟API端点。

变体

在整个浏览器上下文中设置路由使用browserContext.route()或在页面中使用page.route()。这将适用于弹出窗口和打开的链接。

await browserContext.route('**/api/login', route => route.fulfill({
status: 200,
body: 'accept',
}));
await page.goto('https://example.com');

修改请求

// Delete header
await page.route('**/*', async route => {
const headers = route.request().headers();
delete headers['X-Secret'];
await route.continue({ headers });
});

// Continue requests as POST.
await page.route('**/*', route => route.continue({ method: 'POST' }));

您可以对请求进行修改后继续发送。上面的示例移除了传出请求中的一个HTTP头部。

中止请求

您可以使用page.route()route.abort()来中止请求。

await page.route('**/*.{png,jpg,jpeg}', route => route.abort());

// Abort based on the request type
await page.route('**/*', route => {
return route.request().resourceType() === 'image' ? route.abort() : route.continue();
});

修改响应

要修改响应,请使用APIRequestContext获取原始响应,然后将响应传递给route.fulfill()。您可以通过选项覆盖响应中的各个字段:

await page.route('**/title.html', async route => {
// Fetch original response.
const response = await route.fetch();
// Add a prefix to the title.
let body = await response.text();
body = body.replace('<title>', '<title>My prefix:');
await route.fulfill({
// Pass all fields from the response.
response,
// Override response body.
body,
// Force content type to be html.
headers: {
...response.headers(),
'content-type': 'text/html'
}
});
});

全局URL模式

Playwright在网络拦截方法如page.route()page.waitForResponse()中使用简化的glob模式进行URL匹配。这些模式支持基本通配符:

  1. Asterisks:
    • 单个 * 匹配除 / 外的任何字符
    • 双星号 ** 可以匹配包括 / 在内的任何字符
  2. 问号 ? 匹配除 / 外的任意单个字符
  3. 大括号 {} 可用于匹配由逗号 , 分隔的选项列表
  4. 方括号 [] 可用于匹配一组字符
  5. 反斜杠 \ 可用于转义任何特殊字符(注意反斜杠本身需要用 \\ 转义)

示例:

  • https://example.com/*.js 匹配 https://example.com/file.js 但不匹配 https://example.com/path/file.js
  • https://example.com/\\?page=1 匹配 https://example.com/?page=1 但不匹配 https://example.com
  • **/v[0-9]* 匹配 https://example.com/v1/ 但不匹配 https://example.com/vote/
  • **/*.js 匹配 https://example.com/file.jshttps://example.com/path/file.js
  • **/*.{png,jpg,jpeg} 匹配所有图片请求

重要说明:

  • glob模式必须匹配整个URL,而不仅仅是其中的一部分。
  • 在使用通配符进行URL匹配时,请考虑完整的URL结构,包括协议和路径分隔符。
  • 对于更复杂的匹配需求,考虑使用 RegExp 而不是 glob 模式。

WebSockets

Playwright 支持开箱即用的WebSockets检查、模拟和修改。请参阅我们的API mocking guide了解如何模拟WebSockets。

每当创建WebSocket时,都会触发page.on('websocket')事件。该事件包含WebSocket实例,用于进一步的WebSocket帧检查:

page.on('websocket', ws => {
console.log(`WebSocket opened: ${ws.url()}>`);
ws.on('framesent', event => console.log(event.payload));
ws.on('framereceived', event => console.log(event.payload));
ws.on('close', () => console.log('WebSocket closed'));
});

缺失的网络事件与服务工作者

Playwright内置的browserContext.route()page.route()允许您的测试原生地路由请求并执行模拟和拦截操作。

  1. 如果您正在使用Playwright的原生browserContext.route()page.route(),并且发现网络事件缺失,可以通过将serviceWorkers设置为'block'来禁用Service Workers。
  2. 可能是您正在使用像Mock Service Worker (MSW)这样的模拟工具。虽然该工具开箱即用可以模拟响应,但它会添加自己的Service Worker来接管网络请求,从而使这些请求对browserContext.route()page.route()不可见。如果您同时需要网络测试和模拟功能,建议使用内置的browserContext.route()page.route()来实现response mocking
  3. 如果您不仅对使用Service Workers进行测试和网络模拟感兴趣,还想了解如何路由和监听由Service Workers自身发出的请求,请参阅此实验性功能