如何使用 Node.js 进行抓取

How to crawling using Node.js

我不敢相信我问的是一个明显的问题,但我在控制台日志中仍然出错。

控制台在站点中显示类似“[]”的抓取,但我至少检查了 10 次错别字。无论如何,这是 javascript 代码。

我想在站点中抓取。

这是 kangnam.js 文件:

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

const getHTML = async () => {
    try {
        return await axios.get('https://web.kangnam.ac.kr', {
            headers: {
                Accept: 'text/html'
            }
        });
    } catch (error) {
        console.log(error);
    }
};

getHTML()
    .then(html => {
    let ulList = [];
    const $ = cheerio.load(html.data);
    const $allNotices = $("ul.tab_listl div.list_txt");
    
    $allNotices.each(function(idx, element) {
        ulList[idx] = {
            title : $(this).find("list_txt title").text(),
            url : $(this).find("list_txt a").attr('href')
        };
    });
    
    const data = ulList.filter(n => n.title);
    return data;
}). then(res => log(res));

我检查修改了至少10次 然而,Js 仍然抛出这个结果:

root@goorm:/workspace/web_platform_test/myapp/kangnamCrawling(master)# node kangnam.js
[]

伙计,我认为问题是你解析不正确。

$allNotices.each(function(idx, element) {
    ulList[idx] = {
        title : $(this).find("list_txt title").text(),
        url : $(this).find("list_txt a").attr('href')
    };
});

您要解析的数据位于 $(this) 数组的第一个索引中,它实际上只是存储一个 DOM 节点。至于为什么 DOM 会这样存储节点,很可能是因为效率和有效性。但是您要查找的所有数据都包含在这个 Node 对象中。但是, find() 是肤浅的,仅根据您提供的条件检查数组的索引,这是一个字符串搜索。 $(this) 数组只包含一个节点,而不是一个字符串,所以当你为一个字符串调用 .find() 时,它总是 return undefined.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

您需要先访问初始索引并在节点上执行 属性 访问器。您也不需要使用 $(this) ,因为您已经通过 element 参数获得了完全相同的数据。仅使用 element 也更有效,因为您已经获得了需要使用的数据。

  $allNotices.each(function(idx, element) {
      ulList[idx] = {
          title : element.children[0].attribs.title,
          url : element.children[0].attribs.href
      };
  });

现在应该可以正确填充您的数据数组。您应该始终分析要解析的数据结构,因为这是正确解析它们的唯一方法。 不管怎样,我希望我解决了你的问题!