在同學(xué)的建議下我開始學(xué)習(xí)如何抓取一個網(wǎng)頁交播,獲取網(wǎng)頁上的信息。
?
https://book.douban.com/ [豆瓣讀書]
獲取書名
HTTPS和cheerio模塊實現(xiàn)
- 通過HTTPS模塊進(jìn)行獲取整個HTML頁面
??//使用get方法發(fā)送請求
https.get(url,function (res) {
var html = '';
res.on('data',function (data) {
html +=data;
});
res.on('end',function () {
console.log(html);
});
}).on('error',function () {
console.log('爬取頁面錯誤');
});
- 分析所要獲取的信息
可見所有的書籍的名稱都在class為title的div中廷蓉,以及a標(biāo)簽中
- 通過cheerio模塊進(jìn)行對獲取到的html進(jìn)行分析
??//封裝在crawleChapter函數(shù)中
function crawleChapter(html) {
var $ = cheerio.load(html);
var books = $('.title');//獲取class為title的div
var data = [];
books.map(function (node) {
var books = $(this);
var booksName = books.find('a').text().trim();//遍歷div,獲取a標(biāo)簽的文本即書籍的書名信息
data.push(booksName);
});
console.log(data);
}
superagent模塊
可以使用superagent模塊來進(jìn)行與服務(wù)器的交互
superagent.get(url)
.end(function (err, res) {
//請求成功之后進(jìn)行的解析html文件
});