如何使用 Node.js 抓取页面

How can I scrape pages with Node.js

我正在尝试抓取网站,但无法将结果写入 HTML 文件。

我在 node.js 中使用了 cheerio,我的代码如下。

var http = require('http');
var path = require('path');
var request = require('request');
var cheerio = require('cheerio');

http.createServer(function (req, res) {
    res.write('<html><head></head><body>');
        request('http://www.espn.com', function(err, res, html){
            var $ = cheerio.load(html);

            $('a.realStory').each(function(i, element) {
                var node = $(this);
                var text = node.text();
            res.write('<p>'+ text +'</p>');     
            });
        });

  res.end('</body></html>');
}).listen(1337);

如何 运行 这个文件然后转到我的本地主机查看它?

基本实现:

var express = require('express'),
    path = require('path'),
    request = require('request'),
    cheerio = require('cheerio'),
    app = express();
app.get('/', function (req, res) {
    request('http://www.espn.com', function (e, r, html) {
        var $ = cheerio.load(html);
        $('a.realStory').each(function (i, element) {
            var node = $(this);
            var text = node.text();
            res.write('<p>' + text + '</p>');
        });
        res.end();
    });
});
app.listen(process.env.PORT || 1337, function () {
    console.log("Server running..");
});