Hexo文章无损导入Notion

2,582 阅读2分钟

说明

我之前的博客用的 hexo + github,因为更喜欢 Notion 的灵活,因此转了过来,于是就碰到了迁移问题。

Notion 本身是支持 Markdown 导入的, 遇到两个问题:

  • 头部的 yaml 被忽略了,这倒是小问题,因为日期和 tags 不写脚本的话,也需要手工再补一遍
  • code 格式问题比较严重,导过来全部变成了 plaintext 类型,并且换行都没有了,根本没法看

谷歌查询解决方案,找到一个 github 仓库(见文章最后的参考链接),优化了 NotionMarkdown 的渲染,不过要编写 python 脚本导入,而且提供了 Hexo 导入脚本的示例(太赞了)。

下面就是具体的导入操作:

安装 python 支持库

pip install md2notion

python 脚本

💡 注意:python 版本 >= 3.6,建议使用 pyenv 管理版本。
import io
import os.path
import glob
from pathlib import Path
from notion.block import PageBlock
from notion.client import NotionClient
from md2notion.upload import upload

client = NotionClient(
    token_v2="token in your cookies")
page = client.get_block(
    "https://www.notion.so/your-page-path")

for fp in glob.glob("your-hexo-path/source/_posts/*.md", recursive=True):
    with open(fp, "r", encoding="utf-8") as mdFile:
        # Preprocess the Markdown frontmatter into yaml code fences
        mdStr = mdFile.read()
        mdChunks = mdStr.split("---")
        mdStr = (
            f'```yaml'
            f'{mdChunks[1]}'
            f'```'
            f''
            f"{'---'.join(mdChunks[2:])}"
        )
        mdFile = io.StringIO(mdStr)
        mdFile.__dict__["name"] = fp  # Set this so we can resolve images later

        pageName = os.path.basename(fp)[:40]
        newPage = page.children.add_new(PageBlock, title=pageName)
        print(f"Uploading {fp} to Notion.so at page {pageName}")
        # Get the image relative to the markdown file in the flavor that Hexo
        # stores its images (in a folder with the same name as the md file)

        def convertImagePath(imagePath, mdFilePath):
            return Path(mdFilePath).parent / Path(mdFilePath).stem / Path(imagePath)
        upload(mdFile, newPage, imagePathFunc=convertImagePath)

Nobelium 博客

运行上面的脚本,等待导入完成。

如果你想继续基于 Notion 搭建一个类似 Hexo 的博客,那么你可以使用 Nobelium,它是一个开源的 Notion 博客系统,具体搭建过程参考文章后面的链接。

💡 注意: `Hexo` 导过来的文章转 `Nobelium` 模版时,需要整理一下日期、slug、status 等字段。如果前一文章数量比较多,可以琢磨一下能不能写脚本处理。

参考

GitHub - Cobertos/md2notion: A better Notion.so Markdown importer

使用 Nobelium + Vercel 把你的 Notion 变为博客 - 少数派