这里是通过我的代码从 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 添加到您的脚本中:https://stackoverflow.com/a/7474394/5228251
您需要使用此 ^code 和 cheerio 来解析页面。
更新
使用request 和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);
});
希望这会有所帮助。