问题描述
我正在尝试使用Cheerio和Axios检索三个简单的属性:标题,链接和日期https://soundcloud.com/the-herman-show/tracks。我试图遍历“ soundTitle__titleContainer”的列表并解析标题,链接和日期。
当我运行node crawler.js时,我得到一个空数组,但是我应该得到我所请求的信息。感谢您的帮助。
注意:在控制台(Chrome开发工具)中,我运行js let item = document.querySelectorAll('.soundTitle__titleContainer')
,它返回10个项目的NodeList。因此,我知道存在某种东西,而且我至少应该能够返回一个数组。
这是我的循环结构:
let getData = html => {
data = [];
const $ = cheerio.load(html);
$('.soundTitle__titleContainer').each((i,elem) => {
data.push({
index: i,title: $(elem).find('.soundTitle__title span').text(),link: $(elem).find('a.soundTitle__title').attr('href'),date: $(elem).find('relativeTime').text()
});
});
return data;
}
这是我的axios电话:
const url = 'https://soundcloud.com/the-herman-show/tracks';
axios.get(url)
.then(response => {
let html = response.data;
console.log(getData(html));
})
.catch(error => {
console.log(error);
})
以下是Chrome开发工具中检查器的图片:
以下是我要抓取的信息摘要:
我知道这段代码行得通,因为我用来自https://news.ycombinator.com/的数据进行了测试
const axios = require('axios');
const cheerio = require('cheerio');
const url = 'https://news.ycombinator.com';
axios.get(url)
.then(response => {
let html = response.data;
console.log(getData(html));
})
.catch(error => {
console.log(error);
})
let getData = html => {
data = [];
const $ = cheerio.load(html);
$('.athing').each((i,elem) => {
data.push({
title: $(elem).find('.title:last-child').text(),link: $(elem).find('a.storylink').attr('href'),score: $(elem).find('.athing + .score').text()
});
});
return data;
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)