【发布时间】:2019-08-18 00:25:32
【问题描述】:
我正在使用来自多个站点的 nodeJS (TypeScript) 构建一个网络 scraper(我是新手,但从尝试中学习:"D)。
无论如何,问题出在following code 上,当我subscribe 和console.log 返回value 时!什么都没有发生!。
即使console.log 硬string 里面subscribe() 没有显示!!!
但它订阅我的意思是功能可以工作,但我当然需要数据。
构造函数:
constructor() {
this.websitesUrls.subscribe(
data => {
this.intialScraping([data[0]]);
}
);
}
IntialScraping 方法:
intialScraping(newsPapers: { title: string, href: string }[]) {
console.log('Intializing scrapping');
for (let i = 0; i < newsPapers.length; i++) {
const newsPaper = newsPapers[i];
switch (newsPaper.href) {
case "http://test.com":
console.log('Sracping on: ', newsPaper.title);
let uri = newsPaper.href + '/%D8%A3%D8%AE%D8%A8%D8%A7%D8%B1-%D9%88%D8%AA%D9%82%D8%A7%D8%B1%D9%8A%D8%B1'
RxHR.get(uri)
.pipe(
map(data => {
let $ = cheerio.load(data.body);
const articlesUrl = $('#infinite .item > a').map(function (this: any) {
return $(this).attr('href')
}).get();
return articlesUrl;
}),
switchMap(urls => {
let data = [];
for (let i = 0; i < urls.length; i++) {
const url = urls[i];
// console.log('start looping', url);
let data$ = RxHR.get(url).pipe(
map(data => {
let $ = cheerio.load(data.body);
return {
title: $('h1[itemprop=headline]').text().trim(),
image: $('.article-image img').attr('src'),
content: $('.details').text()
};
})
)
data.push(data$); // if i console here there is an output
} // loop ending
return forkJoin(data);
})
).subscribe( data => {
console.log('Working'); // no-output
console.log(data[0].title); // no-output
})
break;
default:
break;
}
}
}
在上面的代码中,我评论 console.log 不工作!
注意:“管道”“switchMap”中的数据变量如果我控制台它会给我数据!
【问题讨论】:
-
一般来说,如果
subscribe函数中的某些东西不起作用,那是因为没有数据到达管道的末端。可能是您的forkJoin没有发出任何内容,因为其中并非所有 Observable 都正确完成。您是否尝试过添加catchError来查看是否有问题?另外,我不能 100% 确定您可以将数组传递给forkJoin。你能试试forkJoin(...data)吗?
标签: javascript node.js typescript web-scraping rxjs