使用Node.js,请求和cheerio从网站上刮下链接?

我试图使用Node.js,请求和cheerio在我学校的课程安排网站上刮取链接。 但是,我的代码没有达到所有主题链接。

链接到课程安排网站在这里 。

以下是我的代码:

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!'); 

我的输出可以在这里find。

正如你可以看到从我的输出,一些链接丢失。 更具体地说,来自“A”,“I(续)”和“R”(续)部分的链接。 这些也是每列的第一部分。

每个部分都包含在它自己的div类名称“courseList_section”,所以我不明白为什么“.courseList_section a”不循环所有链接。 我错过了什么明显的? 任何和所有的见解是非常赞赏的。

先谢谢你!

问题不在于你的代码,而是你试图parsing的那个网站。 HTML标签是无效的。 你正试图parsing.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 --> 

解决scheme。 获取所有链接,忽略那些与任何课程无关的链接。

 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美化 ,并再次检查它。 即使是美化者也不能处理这个标记,表明标签有问题。