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

为何Playwright中拦截并放行请求比不处理更快?

请求拦截放行 vs 全局设置HTTP头的性能对比

我使用Playwright的Page.route拦截所有请求,仅为特定URL添加认证头。测试对比了两种方式下页面到达networkidle状态的耗时:

  • 无差别设置HTTP头(page.set_extra_http_headers)
  • 拦截所有请求后直接放行

结果意外发现,拦截放行的方式在真实网页中速度明显更快,部分场景差距极大:

type=request interception (passthrough) n= 30 std_dev=0.07077  mean=2.66928
type=normal                             n= 30 std_dev=0.24912  mean=12.10215

本地Chrome打开测试URL时,耗时与normal类型相当,但Firefox能很快进入networkidle状态。测试使用的是Playwright 1.40.0及更早版本。

请求路由代码

async def passthrough(route: Route, req: Request):
    await route.continue_()
await page.route("*", passthrough)

测试服务器代码

import asyncio
import random

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/ping', methods=['GET'])
async def ping():
    # 若移除该代码,仍有可测量差异,但差距较小
    await asyncio.sleep(random.random() / 25)
    return "pong"

if __name__ == '__main__':
    app.run(debug=True)

测试页面HTML

<!DOCTYPE html>
<html lang="en">
<body>
    <script>
        function sendRequests() {
            for (let i = 1; i <= 500; i++) {
                fetch('http://127.0.0.1:5000/ping', { method: 'GET' })
                    .then(response => console.log(`Request ${i}: ${response.status}`))
                    .catch(error => console.error(`Request ${i}: ${error.message}`));
            }
        }
        sendRequests();
    </script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 04:01:11