使用Cheerio爬取网站图片无法获取图片URL的问题求助
解决KBDFans商品图片URL爬取失败的问题
你的代码爬不到图片URL主要有两个原因:
- 页面图片采用懒加载机制,初始HTML里的图片元素还未触发加载,因此不存在
lazyloaded类,用这个类做选择器会匹配不到目标元素 - 懒加载图片的真实URL存储在
data-src或data-srcset属性中,而非你尝试获取的srcset
修改后的代码如下:
const url = 'https://kbdfans.com/collections/ready-to-use' axios(url).then(response => { const html = response.data const $ = cheerio.load(html) const arrayData = [] $('.product-block.one-fifth.small-down--one-whole.grid-flex__item').each(function(index){ const description = $(this).find('a.product-block__title-link').text().trim() const price = $(this).find('span.theme-money').text().trim() // 移除lazyloaded类,匹配初始状态的图片元素,获取单张图片URL const img = $(this).find('img.rimage__image.fade-in.lazyautosizes').attr('data-src') // 若需要多尺寸图片集合,可改用data-srcset // const imgSrcset = $(this).find('img.rimage__image.fade-in.lazyautosizes').attr('data-srcset') const id = index arrayData.push({ id, description, price, img }) }) console.log(arrayData) }).catch(err => {console.log(err)})
补充说明
如果data-src返回的是缩略图,想要获取高清图,可以解析data-srcset属性(包含不同分辨率的图片URL),按需提取目标地址:
const srcset = $(this).find('img.rimage__image.fade-in.lazyautosizes').attr('data-srcset') // 分割srcset字符串,提取第一个图片URL const img = srcset ? srcset.split(',')[0].split(' ')[0] : ''
内容的提问来源于stack exchange,提问作者Ranses Canelôn
相关产品推荐
相关产品推荐

