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

使用Node.js+Cheerio爬取网页:标题无法存入数组求助

解决Cheerio爬取标题存入数组的问题

问题分析

你的代码选择器逻辑有误:$(this).find('a').has('.item_description').text() 仅筛选出包含.item_description的a标签,但获取的是整个a标签的文本,没有精准定位到目标的.item_description_title元素,导致无法正确提取所需标题。

修正后的代码

axios(url)
    .then(response => {
        const html = response.data
        const $ = cheerio.load(html)
        const articles = []
        $('.shortcut_navigable').each(function() {
            // 直接定位到目标标题元素并提取文本
            const title = $(this).find('.item_description_title').text().trim()
            articles.push({
                title
            })
        })
        console.log(articles)
    }).catch(err => console.log(err))

关键调整说明

  • 移除了html作为.shortcut_navigable的上下文参数,Cheerio加载后$已绑定整个HTML结构,无需重复传入。
  • 使用$(this).find('.item_description_title')直接定位到目标标题元素,确保只提取该元素的文本内容。
  • 添加.trim()去除文本前后的空白字符,让结果更整洁。

后续扩展存储其他信息

如果需要存储价格、详情链接等其他信息,可按同样方式定位对应元素:

$('.shortcut_navigable').each(function() {
    const title = $(this).find('.item_description_title').text().trim()
    const price = $(this).find('.item_price').text().trim() // 示例:假设价格元素class为item_price
    const detailLink = $(this).find('a').attr('href') // 获取详情页链接
    
    articles.push({
        title,
        price,
        detailLink
    })
})

内容的提问来源于stack exchange,提问作者fluffy-lionz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 18:21:09