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

Playwright操作iframe内reCAPTCHA:超时与无验证码场景处理

Playwright处理reCAPTCHA常见问题解决方法

问题1:超时错误与页面/上下文提前关闭

解决方法:

  • 延长元素等待超时时间:给waitForSelector方法添加timeout参数,默认30000ms(30秒),可根据需求调整为60秒甚至更久。
  • 避免提前关闭资源:确保所有页面操作(点击、表单提交等)完成后,再执行浏览器/上下文关闭操作;用try-catch捕获异常,防止操作中途资源被意外关闭。

问题2:验证码仅部分场景显示,无验证码时避免超时

解决方法:

用try-catch包裹验证码相关定位逻辑,若捕获到超时错误,说明验证码未加载,直接跳过验证步骤,继续执行后续表单提交逻辑。


修改后的完整代码

const { chromium } = require('playwright');

const getHtmlPlaywright = async () => {
  let browser;
  let context;
  let page;
  try {
    browser = await chromium.launch({ chromiumSandbox: false });
    context = await browser.newContext();
    page = await context.newPage();
    await page.goto("https://www.example.com");

    // 尝试处理验证码,失败则跳过
    let captchaHandled = false;
    try {
      // 延长超时至60秒
      const captchaFrame = await page.waitForSelector("iframe[title='reCAPTCHA']", { timeout: 60000 });
      const captchaFrameContent = await captchaFrame.contentFrame();
      // 注意:实际点击的是reCAPTCHA复选框,而非隐藏的textarea
      const captchaCheckbox = await captchaFrameContent.waitForSelector(".recaptcha-checkbox-border", { timeout: 60000 });
      await captchaCheckbox.click();
      // 等待验证完成(按需调整等待时间)
      await page.waitForTimeout(3000);
      captchaHandled = true;
    } catch (err) {
      console.log("未检测到reCAPTCHA,跳过验证");
    }

    // 提交表单
    const formSubmit = await page.waitForSelector("#recaptcha-form input[type='submit']", { timeout: 60000 });
    // 验证码验证完成后,等待提交按钮启用
    if (captchaHandled) {
      await page.waitForFunction(() => !document.querySelector("#recaptcha-form input[type='submit']").disabled);
    }
    await formSubmit.click();

    // 等待页面跳转完成(按需调整)
    await page.waitForNavigation();

    const html = await page.content();
    return html;
  } catch (err) {
    console.error("操作出错:", err);
    throw err;
  } finally {
    // 确保资源被清理
    if (context) await context.close();
    if (browser) await browser.close();
  }
}

关键说明:

  1. 修正原始代码问题:补充async关键字、正确导入chromium、完善URL协议。
  2. 超时控制:所有元素等待都添加了60秒超时参数,可按需调整。
  3. 验证码跳过逻辑:内层try-catch捕获定位超时,标记状态后直接执行后续流程。
  4. 资源安全:finally块确保浏览器/上下文无论成功失败都会关闭,避免资源泄漏。
  5. 定位修正:原始代码中定位的#g-recaptcha-response是隐藏的textarea,实际需点击的是iframe内的.recaptcha-checkbox-border复选框。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 19:32:51