node爬取掘金/csdn文章

前言

平常看到一些好的文章,想在个人博客上转发记录一下,一下一下的去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)
  }
});

实现效果

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

参考

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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值