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

如何用Playwright遍历JSON对象并提取my_id字段值

如何从Playwright获取的API响应中提取threads数组的my_id字段

问题原因

你之前尝试用b[0][12]报错,是因为res.body()返回的是原始二进制数据(Buffer/Uint8Array),不是解析后的JSON对象,自然无法用数组索引访问对象属性。

正确解决方案

要提取目标字段,需要先将响应体解析为JSON对象,再通过键名访问对应值:

完整代码示例

const [response] = await Promise.all([
  page.waitForResponse(res =>
    res.status() === 200 &&
    res.url() === 'https://apples.com/members/msg/get_inbox?filter=all&unread_only=0&last_msg_id=0'
  ),
  page.getByRole('button', { name: 'Continue' }).click()
]);

// 将响应解析为JSON对象
const responseData = await response.json();

// 提取单个my_id(假设threads数组至少有一个元素)
const targetMyId = responseData.threads[0].my_id;
console.log(targetMyId); // 输出:8913

// 遍历threads数组提取所有my_id(如果有多个线程)
responseData.threads.forEach(thread => {
  console.log(`线程ID ${thread.thread_id} 对应的my_id:${thread.my_id}`);
});

补充:优化响应等待逻辑(可选)

如果你需要在waitForResponse中确保响应包含my_id,可以直接解析JSON判断,避免处理原始二进制数据:

page.waitForResponse(async res => {
  if (res.status() !== 200 || res.url() !== 'https://apples.com/members/msg/get_inbox?filter=all&unread_only=0&last_msg_id=0') {
    return false;
  }
  try {
    const data = await res.json();
    // 检查threads数组是否存在且至少有一个元素包含my_id
    return Array.isArray(data.threads) && data.threads.some(thread => 'my_id' in thread);
  } catch (err) {
    // 响应不是JSON格式,直接跳过
    return false;
  }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 20:44:59