Playwright中page.request请求可录制但无法重放的问题
Playwright中page.request系列请求无法重放HAR的问题
问题场景
使用Playwright进行HAR录制与重放时,发现page.request.get/post/put等请求在update: false的重放模式下无法读取已录制的HAR存根,但设置update: true时可以正常录制请求。而改用page.goto实现相同请求时,重放功能正常工作。
无法正常工作的代码
test('replay test', async ({page}) => { await page.routeFromHAR('playwright/har/har.zip', { update: false, url: '**/Time/**' }); const dt = await page.request.get('https://timeapi.io/api/Time/current/zone?timeZone=Europe/Zurich') // 打印录制/重放的时间 console.log((await dt.json()).dateTime) });
可正常工作的代码
test('replay test', async ({page}) => { await page.routeFromHAR('playwright/har/har.zip', { update: false, url: '**/Time/**' }); const dt = await page.goto('https://timeapi.io/api/Time/current/zone?timeZone=Europe/Zurich') // 打印录制/重放的时间 console.log((await dt.json()).dateTime) });
原因解析
page.routeFromHAR仅拦截浏览器上下文发起的请求,而page.request系列方法是Playwright直接发起的独立请求,不属于浏览器页面触发的请求,因此重放模式下不会被页面级的HAR路由规则匹配。
而page.goto是触发浏览器加载页面的操作,对应的请求属于浏览器上下文内的请求,会被page.routeFromHAR正确拦截并重放。
解决方法
要让page.request系列请求也能被HAR重放,需要使用上下文级别的路由context.routeFromHAR,它会覆盖当前浏览器上下文的所有请求,包括Playwright通过page.request发起的请求。
修改后的示例代码:
test('replay test with context route', async ({context, page}) => { await context.routeFromHAR('playwright/har/har.zip', { update: false, url: '**/Time/**' }); const dt = await page.request.get('https://timeapi.io/api/Time/current/zone?timeZone=Europe/Zurich') console.log((await dt.json()).dateTime) });
内容的提问来源于stack exchange,提问作者shout
相关产品推荐
相关产品推荐

