node.js - 无法从 div 获取文本
问题描述
我想mw-content-text
从一些维基百科页面获取 div 的内容(这只是学习 node.js 的示例)我做了这个:
var fetch = require('node-fetch');
var cheerio = require('cheerio');
var fs = require('fs');
var vv = [
'https://en.wikipedia.org/wiki/Ben_Silbermann',
'https://en.wikipedia.org/wiki/List_of_Internet_entrepreneurs'
];
var bo=[],
$;
vv.forEach((t)=>{
fetch(t)
.then(res => res.text())
.then((body) => {
$ = cheerio.load(body);
var finded = $('#mw-content-text').text();
bo.push(finded);
});
});
console.log(bo);
如果我输出正文,它会填充一个包含整个 html 页面的字符串(所以,这一步是可以的),如果我输出$
它包含一个集合(但我不确定它是否被填充,我使用 node.js 命令提示,但看起来它不是正确的工具,对此也有任何建议吗?)
无论如何,变量bo
返回我一个空数组
解决方案
这里的问题是我们在fetch 调用完成之前记录bo 。我建议使用async/await语法来确保我们等待所有获取返回,然后我们可以记录结果。
您可以进行更多处理,例如删除空行、空格等,但这应该不会太难。
var fetch = require('node-fetch');
var cheerio = require('cheerio');
var vv = [
'https://en.wikipedia.org/wiki/Ben_Silbermann',
'https://en.wikipedia.org/wiki/List_of_Internet_entrepreneurs'
];
async function getDivcontent() {
const promises = vv.map(async t => {
const body = await fetch(t).then(res => res.text());
const $ = cheerio.load(body);
return $('#mw-content-text').text();
});
return await Promise.all(promises);
}
async function test() {
let result = await getDivcontent();
console.log("Result:" + result);
}
test();
推荐阅读
- php - 如何在 single.php 中自定义 Wordpress 帖子导航链接默认模板?
- android - 何时在 Android AccessibilityService 中使用 event.getSource() 和 getRootInActiveWindow()
- objective-c - 在视图控制器之间传递字符串
- angular - 为什么我必须手动映射 SystemJS 配置文件中的所有 d3.js 依赖项?
- android - 如何获取所有前台应用程序?
- javascript - 在主 div 之后插入一个空 div
- python - 如何在 python selenium firefox webdriver 中设置标题
- asp.net - 是否可以从现有的 WebForm 项目调用 MVC 项目中的页面
- haskell - 不能定义多个可执行文件
- asp.net-mvc - 从 API 下载文件