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

使用Puppeteer获取连接拒绝页面的目标URL遇问题

获取Connection Refused页面的目标URL(Puppeteer)

当页面跳转到Chrome的chrome-error://chromewebdata/错误页后,直接获取当前页面URL自然拿不到原本的目标地址——因为错误页已经替换了原始导航的URL。可以通过以下几种方式捕获目标URL:

  • 监听请求失败事件
    利用Puppeteer的requestfailed事件,直接捕获失败请求的原始URL,这是最直接的方式:

    page.on('requestfailed', request => {
      if (request.failure().errorText.includes('Connection refused')) {
        console.log('目标URL:', request.url());
      }
    });
    
    // 执行你的导航操作
    await page.goto('目标登录页的初始URL');
    
  • 查看导航历史记录
    错误页加载后,浏览器历史记录里可能保留了之前的目标URL条目:

    const historyEntries = await page.evaluate(() => {
      return Array.from(window.history.entries()).map(entry => entry.url);
    });
    console.log('历史记录中的URL:', historyEntries);
    

    通常最后一条非错误页的URL就是你要找的目标地址。

  • 拦截导航过程记录URL
    在跳转到错误页之前,记录主框架最后一次有效导航的URL:

    let targetUrl;
    page.on('framenavigated', frame => {
      // 只关注主框架的导航
      if (!frame.parentFrame()) {
        const currentUrl = frame.url();
        if (!currentUrl.startsWith('chrome-error://')) {
          targetUrl = currentUrl;
        }
      }
    });
    
    await page.goto('目标登录页的初始URL');
    console.log('目标URL:', targetUrl);
    

这些方法不需要依赖错误页的DOM内容,直接从请求或导航流程中捕获原始目标URL,适配你提到的“已加载完成但显示错误页”的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:20:43