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

如何用Puppeteer+Node.js提取Nike订单尺码并过滤数组元素?

解决方案

一、准确提取订单尺码的正确姿势

你第一段代码的问题是对getProperty的用法完全误解了——这个方法是用来获取DOM元素的原生属性(比如textContent、className),不是用来提取元素内的文本或所谓的“属性名称”。针对Nike订单页的结构,推荐两种可靠的提取方式:

方式1:精准定位目标元素(优先推荐)

假设页面里尺码是和“Product Size”文本配对出现的,比如结构如下:

<div class="item-detail">
  <p class="text-color-secondary">Product Size</p>
  <p class="size-value">US 9.5</p>
</div>

可以先定位到“Product Size”的元素,再取它的相邻兄弟元素文本:

// 找到包含"Product Size"的元素,获取其下一个兄弟的文本
const size = await page.$eval('.text-color-secondary', el => {
  if (el.textContent.trim() === 'Product Size') {
    return el.nextElementSibling?.textContent.trim() || '未找到尺码';
  }
  return null;
});

如果尺码和“Product Size”在同一个元素里(比如<p class="text-color-secondary">Product Size: US 9.5</p>),直接拆分文本即可:

const sizeText = await page.$eval('.text-color-secondary', el => el.textContent.trim());
const size = sizeText.replace('Product Size: ', ''); // 得到纯尺码值

方式2:优化你的page.evaluate代码

如果必须用你第二段的选择器,直接在浏览器上下文里过滤出尺码项,不用等拿到数组再处理:

const sizeInfo = await page.evaluate(() => {
  const sizeTags = document.querySelectorAll(".responsive-body-3-2.mr12-lg.mb2-sm.pt3-sm.flx-gro-sm-1.flex-parent.d-sm-flx.flx-dir-sm-c.flx-jc-sm-sb.flx-ai-sm-fs");
  // 筛选出包含尺码关键词的项,再提取纯尺码值
  return Array.from(sizeTags)
    .map(tag => tag.textContent.trim())
    .filter(text => text.includes('Product Size'))
    .map(text => text.replace(/Product Size:? /i, ''))[0] || '未找到尺码';
});

二、数组过滤指定元素的方法

不管是在浏览器上下文(page.evaluate内)还是Node.js环境,都可以用Array.filter()快速处理:

1. 在浏览器上下文过滤(推荐,减少数据传输)

直接在evaluate里完成过滤,只保留有用内容:

const filteredItems = await page.evaluate(() => {
  const allTags = document.querySelectorAll('.your-selector');
  return Array.from(allTags)
    .map(tag => tag.textContent.trim())
    .filter(item => {
      // 保留包含尺码的项,排除其他
      return item.includes('Product Size');
      // 或者排除特定无关内容:return !item.includes('订单日期') && !item.includes('总价');
    });
});

2. 在Node.js上下文过滤

如果已经把原始数组拿到了Node.js环境,直接用同样的逻辑处理:

// 假设sizeInfo是你拿到的原始数组
const filteredSizes = sizeInfo.filter(item => {
  // 保留包含尺码的项
  return item.includes('Product Size');
  // 或者排除指定元素:return !['订单状态', '支付方式'].includes(item);
});
// 再提取纯尺码值
const pureSizes = filteredSizes.map(item => item.replace(/Product Size:? /i, ''));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:55:18