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

使用JavaScript+Cheerio+Axios抓取Poshmark卖家用户名遇阻求助

解决Poshmark页面卖家用户名抓取问题

问题分析

你当前代码存在几个关键问题:

  • 选择器硬编码nth-child(1),只能定位第一个商品容器,无法遍历所有商品
  • 错误使用find("href")查找属性,Cheerio中获取元素属性需用.attr("href"),而非查找名为href的元素
  • each循环中始终引用itemArea(单个元素),而非当前遍历的元素$(this)
  • 层级选择器过于冗长脆弱,页面结构变动后会直接失效

修正后的代码

const express = require("express");
const cheerio = require("cheerio");
const { default: axios } = require("axios");
const app = express();
const port = process.env.port || 5000;

const url = "https://poshmark.com/category/Men-Jackets_&_Coats?sort_by=like_count&all_size=true&my_size=false";

const fetchData = async () => {
    try {
        // 添加请求头模拟浏览器,避免被反爬拦截
        const res = await axios.get(url, {
            headers: {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"
            }
        });
        const $ = cheerio.load(res.data);

        // 定位所有包含卖家信息的元素,使用更通用的类选择器
        const sellerElements = $(".tile__details__user a");
        
        const sellers = [];
        sellerElements.each(function() {
            // 获取用户名文本并去除空格
            const username = $(this).text().trim();
            // 获取卖家主页链接(可选)
            const sellerHref = $(this).attr("href");
            sellers.push({ username, sellerHref });
            console.log(`卖家用户名:${username}`);
        });

        console.log("\n所有卖家用户名:", sellers);
    } catch (error) {
        console.error("抓取失败:", error.message);
    }
};

fetchData();

关键修正说明

  1. 添加请求头:Poshmark会拦截无浏览器标识的请求,设置User-Agent模拟正常访问
  2. 通用选择器:使用.tile__details__user a直接定位所有卖家的用户名链接,无需依赖冗长的层级选择器
  3. 正确遍历元素:each循环中用$(this)指代当前遍历的元素,确保每个商品都被处理
  4. 属性获取方式:用.attr("href")获取链接属性,.text().trim()去除用户名的多余空格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:18:09