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

我使用node.js,我想得到这个http://myanimelist.net/includes/ajax.inc.php?t=64&id=1页面,并获取我需要的一些数据。 我不能用cheerio做,因为我从来没有遇到过这样的一个页面。 我会很高兴,如果有人告诉我如何parsing这样的页面和哪个节点模块使用它,因为我无法找出它与谷歌,但我明白,这应该是容易的,我只是问一个愚蠢的问题。

这里,通过我的代码简单地从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); 

要testing上面的代码,您需要打开http://myanimelist.net/includes/ajax.inc.php?t=64&id=1 ,并将以上脚本粘贴到Dev Tools inspector – > console中。 当你运行代码时,它会抛出结果,因为没有findjquery页面,所以手动添加jquery到你的脚本通过这个链接: https : //stackoverflow.com/a/7474394/5228251

你需要使用cheerio来parsing页面。

更新

使用请求和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); }); 

希望这可以帮助。