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

本地主机运行Google PageSpeed Insights失败问题求助

问题分析与解决方案

核心问题

你遇到的net::ERR_CONNECTION_FAILED错误本质原因是:PageSpeed Insights(PSI)是Google云端托管服务,它无法访问你本地机器上的localhost:8000服务器。localhost是本地环回地址,仅能在你的机器内部访问,外部云端服务根本无法连接到这个地址。

修正方案

既然要排除外部环境干扰,直接在本地运行Lighthouse(PSI的核心分析引擎)即可,无需依赖云端PSI API。以下是调整后的实现逻辑:

1. 先安装Lighthouse CLI

通过npm全局安装Lighthouse工具:

npm install -g lighthouse

2. 修改代码逻辑

替换原有的PSI API调用,改用本地调用Lighthouse获取性能数据:

import subprocess
import os
import json
import time

# 下载网站文件,添加--convert-links修复本地资源路径问题
subprocess.run(["wget", "-r", "-p", "-np", "--convert-links", url], check=True)

# 启动本地服务器
url_path = url.split("//")[1]
server_process = subprocess.Popen(
    ["python", "-m", "http.server"],
    cwd=os.path.join(os.getcwd(), url_path)
)

try:
    # 等待服务器完全启动(比单次请求更稳妥)
    time.sleep(2)
    
    # 本地调用Lighthouse分析页面性能
    lighthouse_result = subprocess.run(
        ["lighthouse", "http://localhost:8000/", "--output=json", "--quiet", "--chrome-flags=--headless=new"],
        capture_output=True,
        text=True,
        check=True
    )
    
    # 解析性能得分
    data = json.loads(lighthouse_result.stdout)
    performance_score = data['categories']['performance']['score'] * 100
    print(f"{url}: Performance Score = {performance_score:.2f}")
finally:
    # 确保本地服务器被终止
    server_process.kill()

额外优化点

  • wget添加--convert-links参数:修复下载后页面中绝对路径引用外部资源的问题,确保本地页面能正常加载所有资源
  • --chrome-flags=--headless=new:让Lighthouse在无头模式下运行,避免弹出浏览器窗口

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 16:32:28