node爬取掘金/csdn文章

485 阅读2分钟

前言

平常看到一些好的文章,想在个人博客上转发记录一下,一下一下的去copy太麻烦了,因此有了这个想法,能不能通过文章链接,直接取到当前文章,然后放到markdown编辑器里面,这样copy起来不是方便了很多,哈哈哈😄

csdn文章获取

需要借助axios和cheerio 库 这个axios不过多介绍,cheerio是用来分析网页内容,解析html,可以像 jquery 一样操作的一个库

简化代码如下

const axios = require("axios");
const cheerio = require("cheerio");
// csdn文章地址(地址栏)
let url =
  "https://blog.csdn.net/m0_49159526/article/details/125400468?spm=1001.2014.3001.5501";

// 获取文章内容
const getContent = ($) => $("#content_views").html();
// 获取博客
const getBlog = async (url) => {
  let { data } = await axios.get(url);
  let $ = cheerio.load(data);
  let articleHtml = getContent($);
  console.log("文章内容html", articleHtml);
};
getBlog(url);

掘金文章获取

掘金文章的渲染和csdn还有些区别,csdn文章是直接渲染好的,而掘金需要解析文章接口拿到的数据,从中剥离出文章内容并插入到html内 acorn JavaScript解析器 markdown-it 借助markdown-it将markdown转html

const axios = require("axios");
const cheerio = require("cheerio");
const acorn = require("acorn");
const MarkdownIt = require('markdown-it'), md = new MarkdownIt();

let url = "https://juejin.cn/post/7111718092161417229";

axios.get(url).then((res) => {
  const $ = cheerio.load(res.data);
  let str = $("body script")[0].children[0].data;
  let ast = acorn.parse(str, { ecmaVersion: 2020 });
  if (ast) {
    let ps =
      ast.body[0].expression.right.callee.body.body[0].argument.properties;
    let state = ps.find((item) => item.key.name == "state");
    let view = state.value.properties.find((item) => item.key.name == "view");
    let column = view.value.properties.find(
      (item) => item.key.name == "column"
    );
    let entry = column.value.properties.find(
      (item) => item.key.name == "entry"
    );
    let article_info = entry.value.properties.find(
      (item) => item.key.name == "article_info"
    );
    let mark_content = article_info.value.properties.find(
      (item) => item.key.name == "mark_content"
    );
    let result = md.render(mark_content.value.value);
    console.log('文章内容html', result)
  }
});

实现效果

参照上面代码,集成到了自己的网站后台管理系统中,有兴趣的可以注册登录后看下 获取文章

getarticle.png

参考

上述记录,是为了满足我个人网站的需求,也可以直接爬取一些文章到保存为md格式到本地,不多叙述,大家可以参考下 基于node实现CSDN博客导出为markdown 如何备份掘金上的博客?用node写个爬虫吧~