使用node.js和请求提取所有超链接(来自外部网站)

现在我们的应用程序将nodejs.org的源代码写入控制台。 我们希望它写出nodejs.org的所有超链接。 也许我们只需要一行代码即可从body获取链接。

app.js:

 var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); var request = require("request"); request("http://nodejs.org/", function (error, response, body) { if (!error) console.log(body); else console.log(error); }); 

您可能正在寻找jsdom , jquery或cheerio 。 你在做什么叫屏幕抓取,从网站提取数据。 jsdom / jquery提供了一套完整的工具,但cheerio快得多。

这是一个欢呼的例子:

 var request = require('request'); var cheerio = require('cheerio'); var searchTerm = 'screen+scraping'; var url = 'http://www.bing.com/search?q=' + searchTerm; request(url, function(err, resp, body){ $ = cheerio.load(body); links = $('a'); //jquery get all hyperlinks $(links).each(function(i, link){ console.log($(link).text() + ':\n ' + $(link).attr('href')); }); }); 

你select最适合你的。