如何使用节点模块从 ajax.inc.php 页面获取数据



我使用node.js我想获取这个http://myanimelist.net/includes/ajax.inc.php?t=64&id=1页面并获取我需要的一些数据。我无法用cheerio来制作,因为我以前从未遇到过这样的页面。如果有人告诉我如何解析此类页面以及哪个节点模块使用它,我会很高兴,因为我无法用谷歌弄清楚它,但是我知道这应该很容易,我只是在问愚蠢的问题。

在这里,是通过我的代码从 html 输出中提取的简单输出。

{
   "description": "In the year 2071, humanity has colonized several of the planets and moons of the solar system leaving the now uninhabitable surface of planet Earth behind. The Inter Solar System Police attempts to ke...",
   "genres": "Action, Adventure, Comedy, Drama, Sci-Fi, Space",
   "status": "Finished Airing",
   "type": "TV",
   "episodes": "26",
   "score": "8.83",
   "ranked": "#22",
   "popularity": "#31",
   "members": "419,197"
}

下面是从页面中提取信息并将其保存在对象(键:值)对中的代码(即,如上所示);

var $body = $('body');
$('div').children().empty();
var description = $('div').text().trim();
var keys = $('body span').text().split(':');
keys.splice(-1, 1);
$body.children().empty();
var values = $body.text().trim().split('n');
var result = {
    description: description
};
for(var j = 0; j<keys.length; j++) {
    result[(keys[j].toLowerCase().trim())] = (values[j].trim());
}
console.log('result', result);

若要测试上述代码,需要打开 http://myanimelist.net/includes/ajax.inc.php?t=64&id=1 并将上述脚本粘贴到开发工具检查器 -> 控制台中。 当您运行代码时,它将抛出结果,因为找不到 jQuery 页面,因此请通过以下链接手动将 jQuery 添加到脚本中: https://stackoverflow.com/a/7474394/5228251

您需要使用此 ^code 使用 cheerio 来解析页面。

更新

使用请求和欢呼 npm 模块;

安装模块;

$ npm install request --save
$ npm install cheerio --save

使用此脚本;

var cheerio = require('cheerio'),
    request = require('request');
function scrapePage(callback) {
    var result = null;
    var url = 'http://myanimelist.net/includes/ajax.inc.php?t=64&id=1';
    request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            // console.log(body) // Show the HTML for the Page URL.
            var $ = cheerio.load('<body>' + body + '</body>');
            var $body = $('body');
            $('body div').children().empty();
            var description = $('body div').text().trim();
            var keys = $('body span').text().split(':');
            keys.splice(-1, 1);
            $body.children().empty();
            var values = $body.text().trim().split('n');
            result = {
                description: description
            };
            for(var j = 0; j<keys.length; j++) {
                result[(keys[j].toLowerCase().trim())] = (values[j].trim());
            }
        }
        callback(result);
    });
}

用法:

scrapePage(function(result) {
    console.log('result', result);
});

希望这有帮助。

最新更新