网络
网络请求模拟
无需额外配置即可模拟网络请求。只需定义一个自定义路由(Route)来模拟浏览器上下文中的网络请求。
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() 来在单个页面中模拟网络请求:
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 身份验证:
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
httpCredentials: {
username: 'bill',
password: 'pa55w0rd',
}
}
});
const context = await browser.newContext({
httpCredentials: {
username: 'bill',
password: 'pa55w0rd',
},
});
const page = await context.newPage();
await page.goto('https://example.com');
HTTP 代理
你可以配置页面通过 HTTP(S) 代理或 SOCKSv5 代理加载。代理可以全局设置,也可以单独为每个浏览器上下文设置。
你可以选择性地为 HTTP(S) 代理指定用户名和密码,并且可以指定不通过代理的主机。
下面是一个全局代理的例子:
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
proxy: {
server: 'http://myproxy.com:3128',
username: 'usr',
password: 'pwd'
}
}
});
const browser = await chromium.launch({
proxy: {
server: 'http://myproxy.com:3128',
username: 'usr',
password: 'pwd'
}
});
也可以根据上下文指定它:
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();
});
const browser = await chromium.launch();
const context = await browser.newContext({
proxy: { server: 'http://myproxy.com:3128' }
});
网络事件
你可以监控所有的请求和响应:
// 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;
变体
使用 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 端点。
修改请求
// 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'
}
});
});
Glob URL 模式
Playwright 在网络拦截方法(如 page.route() 或 page.waitForResponse())中使用简化的 glob 模式来匹配 URL,这些模式支持基本的通配符:
-
星号:
-
单个
*
匹配除了/
之外的任何字符 -
双星
**
匹配包括/
在内的任何字符
-
-
问号
?
匹配除了/
之外的任何单个字符 -
花括号
{}
可用于匹配用逗号分隔的选项列表
示例:
-
https://example.com/*.js
匹配https://example.com/file.js
,但不匹配https://example.com/path/file.js
-
/**/*.js
匹配https://example.com/file.js
和https://example.com/path/file.js
-
/**/*.{png,jpg,jpeg}
匹配所有图片请求
重要提示:
-
glob 模式必须匹配整个 URL,而不仅仅是其中的一部分。
-
使用 glob 模式匹配 URL 时,请考虑完整的 URL 结构,包括协议和路径分隔符。
-
对于更复杂的匹配需求,考虑使用正则表达式而非 glob 模式。
WebSockets
Playwright 支持 WebSocket 检查、模拟和修改。请查看我们的 API 模拟指南 了解如何模拟 WebSocket。
每当一个 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() 允许您的测试原生地路由请求并执行模拟和拦截。
-
如果你使用了 Playwright 的内置 browserContext.route() 和 page.route(),并且发现网络事件缺失,请通过设置 serviceWorkers 为
'block'
来禁用服务工作者。 -
如果你使用了模拟工具(如 Mock Service Worker,MSW),该工具会添加自己的服务工作者并接管网络请求,从而使它们对 browserContext.route() 和 page.route() 不可见。如果你既需要进行网络测试,又希望进行响应模拟,建议使用内置的 browserContext.route() 和 page.route()。
-
如果你不仅仅依赖服务工作者进行测试和网络模拟,还想监听由服务工作者本身发出的请求,请参见这个实验性特性。