首页 > 解决方案 > 无法从 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返回我一个空数组

标签: node.jscheerionode-fetch

解决方案


这里的问题是我们在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();

推荐阅读