如何使用Cheerio抓取网页中同级的两个div内容
网页抓取解决方案:获取同级div中的图片与信息
问题分析
你当前的核心问题是:图片所在的.store-flyer__front和信息所在的.store-flyer__info是同级元素,第一个代码遍历的是.store-flyer__info,无法访问其兄弟节点的图片;第二个代码尝试遍历父容器,但存在选择器不准确或元素定位错误的情况。
解决步骤与代码示例
1. 确认父容器选择器
首先要确保你遍历的是包含.store-flyer__front和.store-flyer__info的直接父容器。根据网页结构,这个父容器的类名大概率是.store-flyer(而非复数的.store-flyers,后者可能是所有卡片的外层容器)。
2. 正确定位同级元素
在父容器的上下文内,分别通过find()获取图片和信息内容:
// 假设父容器类名为.store-flyer,根据实际页面调整 var leafletList = $('.store-flyer', html).each(function() { const $card = $(this); // 缓存当前父容器,避免重复查找 let leaflet = { title: $card.find('.store-flyer__info h3').text().trim(), // 定位图片所在的div,获取source的srcset image: $card.find('.store-flyer__front source').attr('srcset'), link: $card.find('.store-flyer__info a').attr('href'), validDate: $card.find('.store-flyer__info small').text().slice(3,-1).trim() }; // 处理图片地址为空的情况(比如懒加载用data-srcset) if (!leaflet.image) { leaflet.image = $card.find('.store-flyer__front source').attr('data-srcset'); } leaflets.push(leaflet); });
3. 排查常见问题
- 选择器验证:在遍历父容器时,添加
console.log($card.html())打印当前容器的HTML,确认是否包含.store-flyer__front和.store-flyer__info元素。 - 懒加载处理:部分网站会将图片地址存在
data-srcset而非srcset中,需要根据实际HTML调整属性名。 - 多source标签:如果
.store-flyer__front下有多个source,可以用.first()指定取第一个:$card.find('.store-flyer__front source').first().attr('srcset')。
额外调试技巧
如果仍然无法获取图片地址,可以单独打印图片容器的内容,定位问题:
$('.store-flyer', html).each(function() { console.log("图片容器内容:", $(this).find('.store-flyer__front').html()); });
内容的提问来源于stack exchange,提问作者Schiban
相关产品推荐
相关产品推荐

