我可以在JavaScript中使用从Node.js爬网吗?

时间:2019-04-24 06:14:32

标签: javascript node.js json web-crawler

我是javaScript的新手,正在尝试使用node.js抓取网站。我可以检查控制台日志中的数据,但想使用另一个javaScript文件中的数据。如何获取数据?

问题是我从未使用过node.js。我使用javaScript,所以我知道如何编写代码,但是我不知道后端或服务器的工作方式。

我尝试在本地主机中打开它,但是节点方法(例如require())无效。我发现这是因为节点在浏览器中不起作用。(请参阅?对js很新)

我应该使用捆绑器之类的东西吗?

我认为的步骤是

  • 以某种方式将数据作为json发送
  • 以某种方式获取json数据并进行渲染

这是爬网代码文件。

const axios = require("axios");
const cheerio = require("cheerio");
const log = console.log;

const getHtml = async () => {
  try {
    return await axios.get(URL);
  } catch (error) {
    console.error(error);
  }
};

getHtml()
  .then(html => {
    let ulList = [];
    const $ = cheerio.load(html.data);
    const $bodyList = $("div.info-timetable ul").children("li");


    $bodyList.each(function(i, elem) {
      ulList[i] = {
          screen: $(this).find('a').attr('data-screenname'),
          time: $(this).find('a').attr('data-playstarttime')  
        };
    });

    const data = ulList.filter(n => n.time);
    return data;
  })
  .then(res => log(res));

能否请您解释我应该采取什么步骤?

如果我能理解为什么需要这些步骤,那也很好。

非常感谢!

1 个答案:

答案 0 :(得分:0)

您可以尝试将数据写入JSON文件并继续进行,这是一种方法,然后您可以将数据用作任何js文件中的对象

const appendFile = (file, contents) =>
new Promise((resolve, reject) => {
fs.appendFile(
  file,
  contents,
  'utf8',
  err => (err ? reject(err) : resolve()),
);
 });

getHtml()
 .then(html => {
let ulList = [];
const $ = cheerio.load(html.data);
const $bodyList = $("div.info-timetable ul").children("li");


$bodyList.each(function(i, elem) {
  ulList[i] = {
      screen: $(this).find('a').attr('data-screenname'),
      time: $(this).find('a').attr('data-playstarttime')  
    };
});

const data = ulList.filter(n => n.time);
return data;
})
.then(res => {
   return appendFile('./data.json',res.toString())
}))
.then(done => {log('updated data json')});