我正在尝试抓取一个网站,但我无法将结果写入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);
如何运行此文件,然后转到我的localhost进行查看?
答案 0 :(得分:1)
基本实施:
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..");
});