You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Playwright按下Control+U查看源码时遇Target closed错误求助

解决Playwright中Control+U触发Target closed错误的问题

问题原因

  1. 未正确处理异步方法:page.keyboard.press是异步函数,代码中缺少await关键字,导致后续逻辑未等待按键操作完成就继续执行。
  2. 按键操作引发页面上下文变更:按下Control+U后,浏览器会打开新标签页展示源代码,原页面的Target会因上下文切换被终止,从而触发Target closed错误。

修复方案

方案一:修正异步调用并处理新标签页(不推荐,稳定性差)

若坚持模拟按键操作,需监听新标签页的创建事件,避免原页面上下文丢失:

import { test, expect } from '@playwright/test';

test('Keywords_Main', async ({ page, context }) => {
  await page.goto('https://www.orangehrm.com/');
  // 同时等待新标签页打开和按键执行
  const [sourcePage] = await Promise.all([
    context.waitForEvent('page'),
    page.keyboard.press('Control+U')
  ]);
  // 等待新页面加载完成
  await sourcePage.waitForLoadState();
  // 获取源代码内容
  const sourceContent = await sourcePage.content();
  console.log(sourceContent);
});

方案二:直接获取页面源代码(推荐,更稳定)

自动化场景下无需模拟按键,直接通过Playwright API获取源代码,彻底避免上下文切换问题:

import { test, expect } from '@playwright/test';

test('Keywords_Main', async ({ page }) => {
  await page.goto('https://www.orangehrm.com/');
  // 获取当前页面的HTML内容
  const pageSource = await page.content();
  console.log(pageSource);
  // 若需要包含DOCTYPE的原始源码,可使用evaluate方法
  const rawSource = await page.evaluate(() => document.documentElement.outerHTML);
  console.log(rawSource);
});

关键说明

  • page.content()方法直接返回当前页面的HTML内容,完全替代手动按Control+U查看源代码的需求。
  • 模拟键盘快捷键打开新标签页的方式在自动化中易出现上下文异常,优先使用API直接获取内容更可靠。

内容的提问来源于stack exchange,提问作者Sarah G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 22:20:09