Advertisement
Guest User

Untitled

a guest
Jul 31st, 2014
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Load the http module to create an http server.
  2. var http = require('http');
  3.  
  4.  
  5. // Configure our HTTP server to respond with Hello World to all requests.
  6. var server = http.createServer(function (request, res) {
  7.     res.writeHead(200, "OK", {
  8.         'Content-Type': 'text/html'
  9.     });
  10.     var request = require('request');
  11.     var cheerio = require('cheerio');
  12.  
  13.     request('https://news.ycombinator.com', function (error, response, html) {
  14.         if (!error && response.statusCode == 200) {
  15.             var $ = cheerio.load(html);
  16.             var parsedResults = [];
  17.             $('span.comhead').each(function (i, element) {
  18.                 // Select the previous element
  19.                 var a = $(this).prev();
  20.                 // Get the rank by parsing the element two levels above the "a" element
  21.                 var rank = a.parent().parent().text();
  22.                 // Parse the link title
  23.                 var title = a.text();
  24.                 // Parse the href attribute from the "a" element
  25.                 var url = a.attr('href');
  26.                 // Get the subtext children from the next row in the HTML table.
  27.                 var subtext = a.parent().parent().next().children('.subtext').children();
  28.                 // Extract the relevant data from the children
  29.                 var points = $(subtext).eq(0).text();
  30.                 var username = $(subtext).eq(1).text();
  31.                 var comments = $(subtext).eq(2).text();
  32.                 // Our parsed meta data object
  33.                 var metadata = {
  34.                     rank: parseInt(rank),
  35.                     title: title,
  36.                     url: url,
  37.                     points: parseInt(points),
  38.                     username: username,
  39.                     comments: parseInt(comments)
  40.                 };
  41.                 // Push meta-data into parsedResults array
  42.                 parsedResults.push(metadata);
  43.             });
  44.             // Log our finished parse results in the terminal
  45.             console.log(parsedResults);
  46.             res.write("<div>" + parsedResults + "</div>");
  47.         }
  48.     });
  49.  
  50.     res.write("Hola que tal");
  51.     res.end();
  52. });
  53.  
  54. // Listen on port 8000, IP defaults to 127.0.0.1
  55. server.listen(8000);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement