最后有全部代码,可直接复制拿走运行
先看最终效果
白色字体为文件夹 黑色字体为文件 可以点击实现展开和折叠
生成网页html形式的百度网盘可折叠目录树教程—超详细
前言
目的主要是想让其他人知道自己网盘内有什么文件,但是又不想让其他人直接下载、查看文件内容。
在面向百度编程时发现目前存在的方法只有三种
一、通过读取百度网盘db文件生成txt文件的目录结构,对于文件多的生成后达到了上万行!反而更麻烦了
二、通过百度网盘开放平台 申请接入后 接口可以实现全部的网盘功能 但是对于只想看个目录的我来说又过于繁琐
三、某些网站提供收费制作的服务 虽然符合但是资金又是问题
最后只能在第一种的基础上进行延展
原效果展示
只需要简单改动 把前面的┃ ┃━等符号替换为html中的ul li 开始标签
并根据当前文件/文件夹与上个文件/文件夹的所在文件层来添加对应的结束标签即可
正文
需要的软件及环境
- 百度网盘客户端
用于获取本地缓存的BaiduYunCacheFileV0.db文件 - python 环境
用于执行代码
使用教程
1. 登录百度网盘客户端 获得db文件
DB文件在 百度网盘安装目录\users\用户编码\BaiduYunCacheFileV0.db
例:D:\Install\BaiduNetdisk\users\6042e993975f952575a94cf405cb69a4\BaiduYunCacheFileV0.db
2. 确定文件夹名称!极其重要!
打开百度网盘在右上角搜索 等
因为百度网盘会出现《期末作业.mp4等多个文件》这种命名的文件夹
由于需要根据文件或文件夹添加不同的结束标签,此类文件夹命名会被认为是文件,从而导致最后的目录树被打乱
需要将文件夹名称中的.mp4删除,同理文件夹名称中含有mp3 word pdf 等文件后缀名时,也需要删除掉
例:期末作业.mp4等多个文件 修改为 期末作业等多个文件
3.生成目录树
运行python代码出现下方窗体
DB文件就是刚刚找到的文件地址 选中即可
保存地址 不用多说
点击生成后会在保存地址 生成两份文件
html直接打开即为最终效果 适合小白或要求不高者 拿到就可以使用了
html文件中css和js都是添加好的
txt文件内为生成好的html标签,可以根据自己内容进行二次开发功能
注:在将生成好的html标签复制到html中时需要手动添加一对ul标签 在ul标签中粘贴生成好的html标签
例:
<body>
<ul>
<!--在此处粘贴生成好的html标签-->
</ul>
</body>
txt文件内容
全部代码
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
from tkinter.ttk import *
import sqlite3
import os
filetype_pre = "" # 上一个文件类型
items_pre = 1 # 上一个文件/文件夹所在目录层数
gaps="" # 总层数
def select_db_file():
db_file = askopenfilename(
title="请选择BaiduYunCacheFileV0.db文件", filetypes=[('db', '*.db')])
db.set(db_file)
def select_save_file():
save_file = asksaveasfilename(filetypes=[('文件', '*.txt')])
f.set(save_file+".txt")
def txtTOhtml(path):
'''
param txt文件路径\n
将生成好的html标签写入为html文件
'''
base=[
"<html><head><meta charset='UTF-8'><style> body { margin: 0; background-color: rgb(156, 215, 217); } p { color: aliceblue; } ul { list-style: none; } ul li ul { display: none; } #box1 { flex: 3; } .zk { display: block; } </style><script src='https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js'></script></head><body><div id='box1'><ul><!-- 目录树开始 -->\n",
"\n<!-- 目录树结束 --></ul></div><script> $('li').click(function (event) { obj = $(this).children('ul'); if (!obj.hasClass('zk')) { siblings = $(this).siblings().children('ul'); if (siblings.hasClass('zk')) { siblings.removeClass('zk'); }; $(obj).addClass('zk'); } else { $(obj).removeClass('zk'); }; event.stopPropagation(); }); </script></body></html>"
]
pathportion = os.path.splitext(path) # 分离文件名与扩展名
scratchFile=pathportion[0]+".html" # 拼接html文件名
#向html文件写入
f = open(scratchFile,'w',encoding='utf-8')
with open(path,'r',encoding='utf-8') as fa:
Readeddata = fa.readlines()
f.write(base[0]) #写入html固定头
for x in Readeddata:#写入生成的html标签
f.write(x)
f.write(base[1]) #写入html固定尾
f.close()
def html_tails(gaps):
'''
param gaps 最后的层\n
return html 文档末尾的标签
'''
html_tails=""
for i in range(gaps.count("┃")):
html_tails=html_tails+"</li></ul>"
return html_tails
def htmltxt(filetype_pre, filetypes, item_vary):
'''
获得对应的html标签\n
param filetype_pre 上个文件类型\n
param filetypes 当前文件类型\n
param item_vary 层数差
'''
html = {
"<li><p>": "<li><p>", # 文件夹头
"</p>": "</p>", # 文件夹尾
"<li>": "<li>", # 文件头
"</li>": "</li>", # 文件尾/
"<ul>": "<ul>",
"</ul></li>": "</ul></li>",
"</li></ul></li>": "</li></ul></li>"
}
html_txt = "" #当前文件与上个文件之间的结束标签
html_head = "" #文件/文件夹头标签
html_tail = "" #文件/文件夹尾标签
#True为文件夹 False为文件
if (filetype_pre == ""): # 上个文件类型=空
return html["<li><p>"], html["</p>"]
if (filetypes == True): # 当前文件类型=文件夹
html_head = html["<li><p>"]
html_tail = html["</p>"]
else:
html_head = html["<li>"]
html_tail = html["</li>"]
if (filetype_pre == True): # 上个文件类型=文件夹
if(item_vary==0):
html_txt=html["</li>"]
elif(item_vary==1):
html_txt=html["<ul>"]
elif(item_vary<0):
for i in range(abs(item_vary)):
html_txt=html_txt+html["</li></ul></li>"]
if(filetype_pre==False): #上个文件类型=文件
if(item_vary==0):
html_txt=""
else:
for i in range(abs(item_vary)): #按层数依次补充
html_txt=html_txt+html["</ul></li>"]
return html_txt+html_head, html_tail
def file_type(filename):
'''
判断文件是 文件夹True 还是 文件False
'''
types = [
".mp4", ".mp3", ".ts", ".pdf", ".docx", ".ppt", ".ppts", ".doc", ".7z", ".zip", ".xlsx", ".jpeg",".jpg", ".png", ".heic", ".mov", "3gp", "aac", "ace", "aif", "arj", "asf", "avi", "bin", "bz2", "exe", "gz", "gzip", "img", "iso", "lzh", "m4a", "m4v", "mkv", "mpa", "mpe", "mpeg", "mpg", "msi", "msu", "ogg", "ogv", "pdf", "plj", "pps", "qt", "ra", "rar", "rm", "rmvb", "sea", "sit", "sitx", "tar", "tif", "tiff", "wav", "wma", "wmv", "apk", "m3u8", "apks", "apkm"
]
if "." in filename:
for i in types:
if i in filename:
return False
for i in types:
if i.upper() in filename:
return False
return True
def filetype(filename, item):
'''
param filename 文件名\n
param item 当前目录\n
返回文件前后html标签\n
return 前标签,后标签
'''
#True为文件夹 False为文件
global filetype_pre # 上个文件类型
filetypes = True # 当前文件类型
# 判断当前文件类型
filetypes = file_type(filename)
global items_pre # 上个文件所在目录层数
items = item.count('/') # 当前文件所在目录层数
item_vary = items-items_pre # 当前目录与上个目录 层数变化
html_head = ""
html_tail = ""
html_head,html_tail=htmltxt(filetype_pre,filetypes,item_vary)
filetype_pre = filetypes # 更新上个文件类型
items_pre = items # 更新上个文件所在目录层数
return html_head, html_tail
def write_file(file_dict, f, item, gap=""):
'''
向txt写入
'''
global gaps
if item == "/":
for i in file_dict["/"]:
html_head,html_tail=filetype(i,"/")
f.write(html_head+ i + html_tail+"\n")
i = item + i + "/"
if i in file_dict:
write_file(file_dict, f, i, gap="┃ ")
else:
gap = "┃ " + gap
for i in file_dict[item]:
if(i==""):
print(item)
html_head,html_tail=filetype(i,item)
f.write(html_head+ i + html_tail+"\n")
gaps=""
gaps=gap
i = item + i + "/"
if i in file_dict:
write_file(file_dict, f, i, gap)
def create_baiduyun_filelist():
file_dict = {}
conn = sqlite3.connect(db.get())
cursor = conn.cursor()
cursor.execute("select * from cache_file")
while True:
value = cursor.fetchone()
if not value:
break
#路径
path = value[2]
#文件名
name = value[3]
#大小
size = value[4]
isdir = value[6]
if path not in file_dict:
file_dict[path] = []
file_dict[path].append(name)
else:
file_dict[path].append(name)
with open(f.get(), "w", encoding='utf-8') as fp:
write_file(file_dict, fp, "/")
global gaps
fp.write(html_tails(gaps))
txtTOhtml(fp.name)
root = Tk()
root.title('百度云文件列表生成工具')
db_select = Button(root, text=' 选择DB文件 ', command=select_db_file)
db_select.grid(row=1, column=1, sticky=W, padx=(2, 0), pady=(2, 0))
db = StringVar()
db_path = Entry(root, width=80, textvariable=db)
db_path['state'] = 'readonly'
db_path.grid(row=1, column=2, padx=3, pady=3, sticky=W+E)
save_path = Button(root, text='选择保存地址', command=select_save_file)
save_path.grid(row=2, column=1, sticky=W, padx=(2, 0), pady=(2, 0))
f = StringVar()
file_path = Entry(root, width=80, textvariable=f)
file_path['state'] = 'readonly'
file_path.grid(row=2, column=2, padx=3, pady=3, sticky=W+E)
create_btn = Button(root, text='生成文件列表', command=create_baiduyun_filelist)
create_btn.grid(row=3, column=1, columnspan=2, pady=(0, 2))
root.columnconfigure(2, weight=1)
root.mainloop()
其他
目前没发现有其他原因导致目录树被打乱,如果你按照教程操作后依旧没成功可以留言反馈。
代码引用说明
由于此类文章在网络上被营销号大量转发导致不清楚原作者是哪位
本人参考是站内 中了毒蛇粉的猫 发布在2021-07-14的 批量获取百度网盘文件目录 的文章,并在此基础上做的修改。