批量分类导出语雀知识库下所有文章

背景

笔者从20年开始使用《语雀》该平台做相关的知识库梳理,但是最近的语雀更新,感觉又会走有道云的老路了,所以赶紧将相关的笔记备份出来。
在这里插入图片描述

使用语雀客户端一篇一篇导出太费劲了,正巧看到官方有开放API访问接口 Doc - 文档 (yuque.com)
稍微写了个脚本,实现相关内容

说明

依赖

requests:API请求

pdfkit:转PDF保存

需要修改的内容

  • DATA_PATH:文件保存路径

  • DATA_TYPE:支持 0:MarkDown格式 1:html 2:pdf

  • USER_TOKEN:用户的Token
    访问:https://www.yuque.com/settings/tokens,新建一个Token,允许访问所有的资源吧
    在这里插入图片描述

  • WKHTMLTOPDF_PATH:wkhtmltopdf插件路径
    插件下载地址:https://wkhtmltopdf.org/downloads.html

源码奉上

'''
Description: export YuQue all docs
Author: 是小之禺啊
Date: 2022-11-20
'''
import os
import re
import requests
import pdfkit

# folder path
DATA_PATH="yuque"
# 0: MarkDown 1: html 2: html to pdf
DATA_TYPE=0

# yuque's api
YUQUE_API="https://customspace.yuque.com/api/v2"
# any str, because api must need
USER_AGENT="agent"
# your yuque token , generate at https://www.yuque.com/settings/tokens
USER_TOKEN="***********************************"
# html to pdo tool path, download at https://wkhtmltopdf.org/downloads.html
WKHTMLTOPDF_PATH=r"D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"

class CExportYuQueDocs:
    def __init__(self):
        try:
            self.api = YUQUE_API
            self.headers = {
                "User-Agent": USER_AGENT,
                "X-Auth-Token": USER_TOKEN
            }
            self.data_path = DATA_PATH
            self.doc_type = DATA_TYPE
            self.pdfkit_config = pdfkit.configuration(wkhtmltopdf=WKHTMLTOPDF_PATH)
            self.pdfkit_options = {
                'page-height': '297',
                'page-width': '210',
                'encoding': 'UTF-8',
                'custom-header': [('Accept-Encoding', 'gzip')]
            }
        except:
            raise ValueError("Parameter Error!")

    def login(self):
        """login"""
        request = requests.get(url=self.api + '/user', headers=self.headers)
        if 200 != request.status_code:
            raise ValueError("Token Error!")
        userJson = request.json()
        self.login_id = userJson['data']['login']
        self.uid = userJson['data']['id']
        self.username = userJson['data']['name']
        print(f"{self.username} Login Success!")

    def getRepos(self):
        """get the user's repos"""
        reposRequest = requests.get(self.api + '/users/' + self.login_id + '/repos', headers=self.headers).json()
        reposList = []
        for item in reposRequest['data']:
            # rid=warehouse's is,
            reposList.append({"id": item['id'], "name": item['name']})
        return reposList

    '''
    ' get all docs details in repos
    '''
    def getDocs(self, reposList):
        listDocs = []
        # get all docs info in repos
        for repos in reposList:
            docsRequest = requests.get(self.api + '/repos/' + str(repos['id']) + '/docs',
                                         headers=self.headers).json()
            for item in docsRequest['data']:
                listDocs.append(
                    {
                        "id": repos['id'],
                        "title": item['title'],
                        "description": item['description'],
                        "slug": item['slug'],
                        "name": repos["name"]
                    }
                )

        # get all doc details
        for item in listDocs:
            # get doc details 'GET /repos/:namespace/docs/:slug'
            docDetails = requests.get(self.api + '/repos/' + str(item['id']) + '/docs/' + item['slug'],
                                            headers=self.headers).json()
            if 0 == self.doc_type:
                # convert '\\n' to '\n'
                docDetails_1 = re.sub(r'\\n', "\n", docDetails['data']['body'])
                # delete '<a name="(.*)"></a>'
                docsData = re.sub(r'<a name="(.*)"></a>', "", docDetails_1)
            else:
                docsData = re.sub(r'<!doctype html>', r'<!doctype html><head><link rel="stylesheet" href="http://editor.yuque.com/ne-editor/lake-content-v1.css"></head>',
                                  docDetails['data']['body_html'])

            # return data
            yield docsData, item["name"], item['title']

    '''
    ' save all docs data to disk
    '''
    def saveDocs(self, data, name, title):
        """save docs"""
        if 0 == self.doc_type:
            saveFolder = f"{self.data_path}/md/{name}"
            filePath = saveFolder + f"/{title}.md"
        elif 1 == self.doc_type:
            saveFolder = f"{self.data_path}/html/{name}"
            filePath = saveFolder + f"/{title}.html"
        elif 2 == self.doc_type:
            saveFolder = f"{self.data_path}/pdf/{name}"
            filePath = saveFolder + f"/{title}.pdf"
        else:
            raise ValueError(f"Error Type to Save! Type[{self.doc_type}]")

        # if repos fplder not exist
        if not os.path.exists(saveFolder):
            os.makedirs(saveFolder)

        # if file exist
        if os.path.exists(filePath):
            try:
                os.remove(filePath)
            except Exception as e:
                raise ValueError(f"File [{filePath}] is occupied!")

        # try save data
        try:
            if 2 == self.doc_type:
                # convert html data to pdf
                pdfkit.from_string(data, filePath, configuration=self.pdfkit_config, options=self.pdfkit_options)
            else:
                with open(filePath, 'a', encoding="utf-8") as fp:
                    fp.writelines(data)
            print(f"Save [{filePath}] Success!")
        except Exception as e:
            print(f"Save [{filePath}] Failed!")

    '''
    ' start fork docs
    '''
    def start(self):
        # login
        self.login()
        # get repos
        reposList = self.getRepos()
        # get all doc in every repos
        for item in self.getDocs(reposList):
            self.saveDocs(item[0], item[1], item[2])


if __name__ == "__main__":
    yq = CExportYuQueDocs()
    yq.start()

执行结果

在这里插入图片描述

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
爬虫(Web Crawler)是一种自动化程序,用于从互联网上收集信息。其主要功能是访问网页、提取数据并存储,以便后续分析或展示。爬虫通常由搜索引擎、数据挖掘工具、监测系统等应用于网络数据抓取的场景。 爬虫的工作流程包括以下几个关键步骤: URL收集: 爬虫从一个或多个初始URL开始,递归或迭代地发现新的URL,构建一个URL队列。这些URL可以通过链接分析、站点地图、搜索引擎等方式获取。 请求网页: 爬虫使用HTTP或其他协议向目标URL发起请求,获取网页的HTML内容。这通常通过HTTP请求库实现,如Python中的Requests库。 解析内容: 爬虫对获取的HTML进行解析,提取有用的信息。常用的解析工具有正则表达式、XPath、Beautiful Soup等。这些工具帮助爬虫定位和提取目标数据,如文本、图片、链接等。 数据存储: 爬虫将提取的数据存储到数据库、文件或其他存储介质中,以备后续分析或展示。常用的存储形式包括关系型数据库、NoSQL数据库、JSON文件等。 遵守规则: 为避免对网站造成过大负担或触发反爬虫机制,爬虫需要遵守网站的robots.txt协议,限制访问频率和深度,并模拟人类访问行为,如设置User-Agent。 反爬虫应对: 由于爬虫的存在,一些网站采取了反爬虫措施,如验证码、IP封锁等。爬虫工程师需要设计相应的策略来应对这些挑战。 爬虫在各个领域都有广泛的应用,包括搜索引擎索引、数据挖掘、价格监测、新闻聚合等。然而,使用爬虫需要遵守法律和伦理规范,尊重网站的使用政策,并确保对被访问网站的服务器负责。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值