本帖最后由 ligxi 于 2020-5-28 21:09 编辑
文泉书籍添加目录的自动脚本代码:
[Python] 纯文本查看 复制代码 import requests
import fitz
import os
# 功能:打开文件并添加目录
pdf = input('请输入需要添加目录的PDF完整文件名:')
#
root = os.getcwd()
# 解决cmd导致的符号问题。
if '--' in pdf:
pdf = pdf.replace('--', '——')
#
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36",
'x-requested-with': 'XMLHttpRequest',
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
#
wq_url = 'https://wqbook.wqxuetang.com/v1/book/catatree?bid=%s' % input('请输入书籍的链接或bid:').split('/')[-1]
res = requests.get(url=wq_url, headers=headers)
if res.status_code == 200:
print('目录信息获取成功!正在添加目录...')
#
doc = fitz.open(pdf)
toc = []
#
data = res.json()['data']
for d in data:
toc.append([int(d['level']), d['label'], int(d['pnum'])])
if 'children' in d:
for c in d['children']: toc.append([int(c['level']), c['label'], int(c['pnum'])])
#
doc.setToC(toc)
pdf = pdf.split('\\')[-1]
doc.save('%s\\New_%s' % (root, pdf))
doc.close()
print('目录添加完毕!文件保存的位置:%s\\New_%s' % (root, pdf))
else:
print('目录信息获取失败,请重试!')
|