我的Node JS控制台正在显示我想要的文本,为什么不能将其另存为字符串?

时间:2018-07-03 04:32:21

标签: javascript node.js

我没有接受过正式的代码培训,这是我第一次尝试Javapscript项目,现在我完成99.9%的工作,挂在这样一个简单的问题上实在令人沮丧。

我将https://www.codementor.io/johnnyb/how-to-write-a-web-scraper-in-nodejs-du108266t中的以下抓取代码拼接在一起,并将其应用于其他目标网站:

// Define the scrape function
function scrape(url, data, cb) {
    // 1. Create the request
    req(url, (err, body) => {
        if (err) { return cb(err); }

        // 2. Parse the HTML
        let $ = cheerio.load(body)
          , pageData = {}
          ;

        // 3. Extract the data
        Object.keys(data).forEach(k => {
            pageData[k] = $(data[k]).text();
        });

        // Send the data in the callback
        cb(null, pageData);
    });
}

// Extract some data from a website
scrape("http://www.esbnyc.com/explore/tower-lights", {
    // Get the website title (from the top header)
    title: ".view-empty #page-title"
}, (err, data) => {
    console.log(err || data);
});

我很高兴看到它有效!所显示的控制台日志(几乎,我想摆脱刮取的网络文本之前的“ title:”)完全符合我的要求,并且我认为将这些信息添加到字符串中很麻烦。

3小时后,我摸索着并尝试了所有错误的答案,我意识到我离解决方案还很近。我只想将自己在日志中看到的信息(例如,“今晚,帝国大厦将以其签名的白色点亮”)保存为字符串,形式为Const / Var / every。但是到目前为止,我能做到的最好的是什么也没有或者是“未定义的”。

0 个答案:

没有答案
相关问题