在服务器页面上将抓取的数据排序为 table

Sort scraped Data into table on server page

您好,我目前正在编写一个爬虫脚本,我已经能够从 2 个元素中爬取。在此测试状态下,到目前为止我还没有数据库设置。所以我想我只是将其直接排序到我的服务器页面。这是我的工作代码

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

http.createServer(function (req, res) {
request('http://www.xscores.com/soccer', function (error, response,
    html) {
    if (!error && response.statusCode == 200) {
        var $ = cheerio.load(html);
        var HomeTeam = "";
        var AwayTeam = "";

        $('div.score_home_txt.score_cell.wrap').each(function (i, element) {
            var a = $(this).text();
            var a = a.toLowerCase();
            HomeTeam += "<tr><td>" + a + "</td>";
            //console.log(a);

        });
        $('div.score_away_txt.score_cell.wrap').each(function (i, element) {
            var b = $(this).text();
            var b = b.toLowerCase();
            AwayTeam += "<td>" + b + "</td><tr>";
            //console.log(b);

        });

        var html = "<table><th>" + "HomeTeam</th><th>AwayTeam</th>" + HomeTeam + AwayTeam + "</table>"
        res.writeHead(200, {
            'Content-Type': 'text/html'
        });
        res.end(html);
    }
});
}).listen(8080);
console.log('Server is running at http://178.62.253.206:8080/');

计划将其排序在 table 中,在 Col A 中有 2 列 Home,在 ColB 中为 Away,但我有点不确定如何编写它以便正确排序。

上面的代码将其排序为一行。我尝试了几种不同的方法,但还没有找到正确的方法:/

如有任何帮助,我们将不胜感激

弗雷德里克

您需要找到一个常见的 parent,查看您正在抓取的网站 .score_line 看起来是一个合理的选择

// assume we're always going to return html
res.set('Content-Type', 'text/html');
// hit API
request('http://www.xscores.com/soccer', (err, response, html) => {
  if (err || response.statusCode !== 200) {
    // log error internally
    console.error(err ? err.message : `API status code: ${response.statusCode}`);
    // return client response
    return res.status(500).send('<b>Internal Server Error</b>');
  }

  const $ = cheerio.load(html);
  const rows = [];
  // find each row
  $('.score_line').each((i, el) => {
    // extract each column
    const homeScore = el.find('.score_home.score_cell.wrap').text().toLowerCase();
    const awayScore = el.find('.score_away.score_cell.wrap').text().toLowerCase();
    // build row
    rows.push(`<tr><td>${homeScore}</td><td>${awayScore}</td></tr>`);
  });
  // build & send table
  res.send(`<table>${rows.join('')}</table>`);
});