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

Playwright无法修改请求体?问题排查求助

问题原因及修复方案

核心错误点

  • 修改了只读请求对象:route.request.post_data_json是Playwright提供的只读属性,你修改这个字典不会改变实际发送的请求内容,pprint输出的只是你修改后的本地字典,并非真正发往服务器的请求体。
  • 请求体格式不匹配:目标请求大概率是JSON格式,但你用urlencode把数据转成了表单编码格式,和原请求的Content-Type不匹配,导致实际发送的内容不符合预期,DevTools里自然看不到正确的修改效果。

修复后的代码

import json
from urllib.parse import urlencode
from playwright.async_api import Route
import pprint

async def handle_uri_route(route: Route):
    response = await route.fetch()
    response_json = await response.json()
    reg_notification_uri = response_json['confirmUri']
    await page.route(reg_notification_uri, modify_notification_uri)
    await route.continue_()

async def modify_notification_uri(route: Route):
    # 复制原请求体字典,避免操作只读对象
    post_data = dict(route.request.post_data_json)
    post_data['notificationUi'] = 'https://httpbin.org/anything'
    
    # 序列化为JSON字符串,匹配原请求的Content-Type
    modified_post_data = json.dumps(post_data)
    await route.continue_(post_data=modified_post_data)
    
    # 打印修改后的实际数据,而非原请求的只读对象
    pprint.pprint(post_data)

await page.route(re.compile(r'api\/common\/v1\/register_notification_uri\?'), handle_uri_route)

关键说明

  1. 复制原请求体:用dict(route.request.post_data_json)创建可修改的副本,绕过只读属性限制。
  2. 匹配请求格式:如果原请求是JSON类型,必须用json.dumps()生成JSON字符串;如果是表单请求才用urlencode,别搞混格式。
  3. 正确验证修改:打印你自己修改后的post_data字典,而不是route.request.post_data_json——后者永远是原请求的内容,不会随你的修改变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:25:30