爬取地址
使用到的庫
- superagent (頁面數(shù)據(jù)下載)
- cheerio (頁面數(shù)據(jù)解析)
代碼
app.js
// 引入依賴
const superagent = require('superagent'); // superagent是nodejs里一個非常方便的客戶端請求代碼模塊
const cheerio = require('cheerio'); // 可以理解為一個Node.js版本的Jquery
// 爬取地址
const url = 'https://www.thepaper.cn/';
// 讀取頁面數(shù)據(jù)
superagent.get(url).end((err, res) => {
if (err) throw Error(err);
let postlist = getFilterHtml(res.text);
// 存入數(shù)據(jù)庫操作...
})
// 過濾數(shù)據(jù)
function getFilterHtml(html) {
let $ = cheerio.load(html); // 使用cheerio
let postList = []; // 存放新聞列表的數(shù)組
// F12分析后的節(jié)點數(shù)據(jù),用Jquery的語法進行過濾、摘取
$('#listContent .news_li').each((index, item) => {
let elem = $(item);
let post = {
icon: elem.find('.tiptitleImg img').attr('src'),
title: elem.find('h2 a').text(),
intro: elem.find('p').text(),
link: elem.find('h2 a').attr('href'),
target: elem.find('.pdtt_trbs a').text(),
hot: elem.find('.pdtt_trbs .trbszan').text()
}
postList.push(post);
})
return postList;
}
最后
本文到此結(jié)束,希望以上內(nèi)容對你有些許幫助,如若喜歡請記得點個贊跟關(guān)注哦 ??
image
微信公眾號
「前端宇宙情報局」,將不定時更新最新、實用的前端技巧/技術(shù)性文章,歡迎關(guān)注,一起學(xué)習(xí) ??