【问题标题】:Scraping links from website using Node.js, request, and cheerio?使用 Node.js、request 和 Cheerio 从网站上抓取链接?
【发布时间】:2016-05-20 03:48:49
【问题描述】:

我正在尝试使用 Node.js、request 和 Cheerio 在我学校的课程安排网站上抓取链接。但是,我的代码并未到达所有主题链接。

链接到课程安排网站here

下面是我的代码:

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

var app = express();

app.get('/subjects', function(req, res) {
  var URL = 'http://courseschedules.njit.edu/index.aspx?semester=2016s';

  request(URL, function(error, response, body) {
    if(!error) {
      var $ = cheerio.load(body);

      $('.courseList_section a').each(function() {
        var text = $(this).text();
        var link = $(this).attr('href');

        console.log(text + ' --> ' + link);
      });
    }
    else {
      console.log('There was an error!');
    }
  });
});

app.listen('8080');
console.log('Magic happens on port 8080!');

我的输出可以在here找到。

从我的输出中可以看出,缺少一些链接。更具体地说,来自“A”、“I(继续)”和 R“(继续)”部分的链接。这些也是每列的第一部分。

每个部分都包含在其自己的 div 中,类名为“courseList_section”,所以我不明白为什么“.courseList_section a”不会遍历所有链接。我错过了一些明显的东西吗?非常感谢任何和所有的见解。

提前谢谢你!

【问题讨论】:

  • 我看不到任何缺失的链接
  • @Oleander 我的输出从 BIO 开始,我的代码不会遍历“A”部分中的任何链接:ACC、ACCT、AD、ARCH 和 AS。与“I(续)”和“R(续)”部分相同。

标签: javascript html node.js web-scraping cheerio


【解决方案1】:

问题不在于您的代码,而在于您尝试解析的站点。 HTML 标记无效。您正在尝试解析 .courseList_section 中的所有内容,但标签看起来像这样。

<span> <!-- Opening tag -->
    <div class='courseList_section'>
      <a href='index.aspx?semester=2016s&ƒ=ACC '>ACC  - Accounting/Essex CC</a>
      </span> <!-- Invalid closing tag for the first span, menaing that .courseList_section will be closed instead

<!-- Suddenly this link is outside the .courseList_section tag, meaning that it will be ignored by cheerio -->
<a href='index.aspx?semester=2016s&subjectID=ACCT'>ACCT - Accounting</a>
  <!-- and so on -->

解决方案。获取所有链接并忽略与任何课程无关的链接。

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

var URL = 'http://courseschedules.njit.edu/index.aspx?semester=2016s';

request(URL, function(error, response, body) {
  if(error) { return  console.error('There was an error!'); }

  var $ = cheerio.load(body);

  $('a').each(function() {
    var text = $(this).text();
    var link = $(this).attr('href');

    if(link && link.match(/subjectID/)){
      console.log(text + ' --> ' + link);
    };
  });
});

下次,尝试直接查看 HTML,看看它是否正常。如果它看起来像 ****,请将其通过 HTML beautifier 并再次检查。甚至美化器也无法处理这个表明标签有问题的标记。

【讨论】:

    猜你喜欢
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多