本文目录导读:

浏览器书签整理(Chrome/Edge 扩展版)
// bookmark_organizer.js
(function() {
'use strict';
// 配置选项
const config = {
removeDuplicates: true, // 删除重复书签
removeBrokenLinks: true, // 删除失效链接
sortByCategory: true, // 按分类排序
maxDepth: 3 // 最大文件夹深度
};
class BookmarkOrganizer {
constructor() {
this.bookmarkTree = null;
this.duplicates = [];
this.brokenLinks = [];
}
// 初始化
async init() {
try {
this.bookmarkTree = await chrome.bookmarks.getTree();
await this.scanBookmarks(this.bookmarkTree[0]);
await this.cleanDuplicates();
await this.cleanBrokenLinks();
await this.sortBookmarks();
return {
success: true,
message: '书签整理完成',
stats: {
duplicates: this.duplicates.length,
brokenLinks: this.brokenLinks.length
}
};
} catch (error) {
console.error('书签整理失败:', error);
return { success: false, error: error.message };
}
}
// 扫描所有书签
async scanBookmarks(node) {
if (node.url) {
// 检查重复
if (config.removeDuplicates) {
const existing = this.findDuplicate(node);
if (existing) {
this.duplicates.push(node.id);
}
}
// 检查失效链接
if (config.removeBrokenLinks) {
const isValid = await this.checkLink(node.url);
if (!isValid) {
this.brokenLinks.push(node.id);
}
}
}
if (node.children) {
for (const child of node.children) {
await this.scanBookmarks(child);
}
}
}
// 查找重复书签
findDuplicate(node) {
// 实现去重逻辑
return null;
}
// 检查链接有效性
async checkLink(url) {
try {
const response = await fetch(url, { method: 'HEAD' });
return response.ok;
} catch {
return false;
}
}
// 清理重复书签
async cleanDuplicates() {
for (const id of this.duplicates) {
await chrome.bookmarks.remove(id);
}
}
// 清理失效链接
async cleanBrokenLinks() {
for (const id of this.brokenLinks) {
await chrome.bookmarks.remove(id);
}
}
// 排序书签
async sortBookmarks() {
const root = await chrome.bookmarks.getTree();
// 实现排序逻辑
}
}
// 执行整理
const organizer = new BookmarkOrganizer();
organizer.init().then(result => {
console.log('整理结果:', result);
});
})();
通用书签 HTML 文件整理脚本
# bookmark_organizer.py
import json
import re
from datetime import datetime
from collections import defaultdict
class BookmarkHTMLParser:
"""解析书签HTML文件"""
def __init__(self, html_content):
self.html = html_content
self.bookmarks = []
self.categories = defaultdict(list)
def parse(self):
"""解析HTML书签文件"""
# 提取所有书签链接
pattern = r'<A HREF="([^"]+)"[^>]*>([^<]+)</A>'
matches = re.findall(pattern, self.html, re.IGNORECASE)
# 提取文件夹结构
folder_pattern = r'<DT><H3[^>]*>([^<]+)</H3>'
folders = re.findall(folder_pattern, self.html)
for url, title in matches:
bookmark = {
'url': url,
'title': title.strip(),
'added_date': datetime.now().isoformat(),
'category': self._get_category(url, title)
}
self.bookmarks.append(bookmark)
self.categories[bookmark['category']].append(bookmark)
return self.bookmarks
def _get_category(self, url, title):
"""根据URL和标题自动分类"""
categories = {
'social': ['facebook', 'twitter', 'linkedin', 'instagram'],
'work': ['github', 'gitlab', 'jira', 'slack'],
'news': ['news', 'blog', 'medium', 'reddit'],
'shopping': ['amazon', 'ebay', 'aliexpress', 'shopify'],
'education': ['coursera', 'udemy', 'khan', 'wikipedia']
}
url_lower = url.lower()
title_lower = title.lower()
for category, keywords in categories.items():
if any(keyword in url_lower or keyword in title_lower for keyword in keywords):
return category
return 'other'
def remove_duplicates(self):
"""去除重复书签"""
seen = set()
unique_bookmarks = []
for bookmark in self.bookmarks:
key = (bookmark['url'], bookmark['title'])
if key not in seen:
seen.add(key)
unique_bookmarks.append(bookmark)
self.bookmarks = unique_bookmarks
return len(seen)
class BookmarkOrganizer:
"""书签整理器"""
def __init__(self, input_file, output_file):
self.input_file = input_file
self.output_file = output_file
self.parser = None
def organize(self):
"""执行整理"""
try:
# 读取输入文件
with open(self.input_file, 'r', encoding='utf-8') as f:
html_content = f.read()
# 解析书签
self.parser = BookmarkHTMLParser(html_content)
bookmarks = self.parser.parse()
# 去重
duplicates_removed = self.parser.remove_duplicates()
# 生成整理后的HTML
organized_html = self._generate_html(bookmarks)
# 保存输出
with open(self.output_file, 'w', encoding='utf-8') as f:
f.write(organized_html)
return {
'success': True,
'total': len(bookmarks),
'duplicates_removed': duplicates_removed,
'categories': len(self.parser.categories)
}
except Exception as e:
return {'success': False, 'error': str(e)}
def _generate_html(self, bookmarks):
"""生成整理后的HTML文件"""
html = '''<!DOCTYPE NETSCAPE-Bookmark-file-1>
<!-- This is an automatically generated file.
It will be read and overwritten.
DO NOT EDIT! -->
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">书签整理</TITLE>
<H1>书签</H1>
<DL><p>
<DT><H3 ADD_DATE="''' + str(int(datetime.now().timestamp())) + '''">整理书签</H3>
<DL><p>
'''
# 按分类组织
for category, items in self.parser.categories.items():
html += f' <DT><H3>{category.upper()}</H3>\n'
html += ' <DL><p>\n'
for bookmark in items:
html += f' <DT><A HREF="{bookmark["url"]}" ADD_DATE="{bookmark["added_date"]}">{bookmark["title"]}</A>\n'
html += ' </DL><p>\n'
html += ''' </DL><p>
</DL><p>
'''
return html
# 使用示例
def main():
# 创建整理器
organizer = BookmarkOrganizer(
input_file='bookmarks.html',
output_file='organized_bookmarks.html'
)
# 执行整理
result = organizer.organize()
if result['success']:
print(f"书签整理完成!")
print(f"总共: {result['total']} 个书签")
print(f"去除重复: {result['duplicates_removed']} 个")
print(f"分类: {result['categories']} 个类别")
else:
print(f"整理失败: {result['error']}")
if __name__ == "__main__":
main()
使用方法
浏览器扩展版
- 创建 Chrome 扩展项目
- 添加
bookmark权限 - 在 popup.html 中调用脚本
HTML 文件版
# 安装依赖 pip install -r requirements.txt # 运行整理 python bookmark_organizer.py
功能扩展建议
// 额外功能:书签标签系统
function addTagSystem() {
// 添加自定义标签
bookmarks.forEach(bookmark => {
bookmark.tags = extractTags(bookmark.title);
});
}
// 智能推荐
function smartRecommend() {
// 基于使用频率推荐
// 基于相关度排序
}
// 备份系统
function backupBookmarks() {
// 自动备份到云端
// 版本控制
}
选择哪个版本取决于你的具体需求,浏览器扩展版适合日常使用,Python 版适合批量处理和自定义规则。