本文目录导读:

我来提供一个支持多种浏览器的自动收藏网页脚本解决方案。
方法1:书签脚本(Bookmarklet)
创建一个可以直接拖拽到书签栏的JavaScript书签:
javascript:(function(){
// 获取当前页面信息
var title = document.title;
var url = window.location.href;
var description = '';
// 尝试获取页面描述
var metaDesc = document.querySelector('meta[name="description"]');
if (metaDesc) {
description = metaDesc.content;
}
// 创建收藏数据
var bookmark = { title,
url: url,
description: description,
date: new Date().toISOString()
};
// 保存到localStorage
var bookmarks = JSON.parse(localStorage.getItem('autoBookmarks') || '[]');
bookmarks.push(bookmark);
localStorage.setItem('autoBookmarks', JSON.stringify(bookmarks));
alert('页面已收藏成功!\n标题: ' + title);
})();
方法2:浏览器扩展脚本
Chrome扩展manifest.json
{
"manifest_version": 3,
"name": "Auto Bookmark",
"version": "1.0",
"description": "自动收藏网页",
"permissions": [
"bookmarks",
"activeTab",
"storage"
],
"action": {
"default_popup": "popup.html",
"default_icon": "icon.png"
},
"background": {
"service_worker": "background.js"
}
}
popup.html
<!DOCTYPE html>
<html>
<head>
<style>
body {
width: 300px;
padding: 15px;
font-family: Arial, sans-serif;
}
button {
width: 100%;
padding: 10px;
margin: 5px 0;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<h3>自动收藏</h3>
<button id="saveBookmark">收藏当前页面</button>
<button id="saveAllTabs">收藏所有标签页</button>
<button id="autoSave">开启自动收藏</button>
<div id="status"></div>
<script src="popup.js"></script>
</body>
</html>
popup.js
document.getElementById('saveBookmark').addEventListener('click', async () => {
const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
chrome.bookmarks.create({ tab.title,
url: tab.url
}, (bookmark) => {
document.getElementById('status').textContent = '收藏成功!';
setTimeout(() => {
document.getElementById('status').textContent = '';
}, 2000);
});
});
document.getElementById('saveAllTabs').addEventListener('click', async () => {
const tabs = await chrome.tabs.query({currentWindow: true});
let count = 0;
for (let tab of tabs) {
chrome.bookmarks.create({
parentId: '1', // 使用书签栏
title: tab.title,
url: tab.url
}, () => {
count++;
if (count === tabs.length) {
document.getElementById('status').textContent = `已收藏 ${count} 个页面`;
}
});
}
});
document.getElementById('autoSave').addEventListener('click', () => {
chrome.storage.local.get(['autoSave'], (result) => {
const newState = !result.autoSave;
chrome.storage.local.set({autoSave: newState}, () => {
const button = document.getElementById('autoSave');
button.textContent = newState ? '关闭自动收藏' : '开启自动收藏';
button.style.backgroundColor = newState ? '#f44336' : '#4CAF50';
});
});
});
background.js
// 监听标签页更新
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete') {
chrome.storage.local.get(['autoSave'], (result) => {
if (result.autoSave && tab.url) {
// 检查是否已收藏
chrome.bookmarks.search({url: tab.url}, (bookmarks) => {
if (bookmarks.length === 0) {
chrome.bookmarks.create({
title: tab.title,
url: tab.url
});
console.log(`自动收藏: ${tab.title}`);
}
});
}
});
}
});
// 监听书签变化
chrome.bookmarks.onCreated.addListener((id, bookmark) => {
chrome.notifications.create({
type: 'basic',
iconUrl: 'icon.png', '书签已添加',
message: bookmark.title
});
});
方法3:Tampermonkey/Greasemonkey脚本
// ==UserScript==
// @name 自动收藏网页
// @namespace http://tampermonkey.net/
// @version 1.0
// @description 自动收藏当前网站到本地存储
// @author You
// @match *://*/*
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_listValues
// ==/UserScript==
(function() {
'use strict';
// 配置
const config = {
autoSave: false, // 是否自动保存
saveOnVisit: true, // 访问时保存
saveOnClose: true // 关闭时保存
};
// 页面加载时保存
if (config.saveOnVisit) {
saveBookmark('visited');
}
// 页面关闭时保存
if (config.saveOnClose) {
window.addEventListener('beforeunload', function() {
saveBookmark('closed');
});
}
function saveBookmark(reason) {
const title = document.title;
const url = window.location.href;
// 获取已保存的书签
let bookmarks = getBookmarks();
// 检查是否已存在
const exists = bookmarks.some(b => b.url === url);
if (!exists) {
bookmarks.push({
title: title,
url: url,
timestamp: new Date().toISOString(),
reason: reason
});
saveBookmarks(bookmarks);
console.log(`书签已保存: ${title} (${reason})`);
}
}
function getBookmarks() {
try {
return JSON.parse(GM_getValue('auto_bookmarks', '[]'));
} catch (e) {
return [];
}
}
function saveBookmarks(bookmarks) {
GM_setValue('auto_bookmarks', JSON.stringify(bookmarks));
}
// 添加快捷键 Ctrl+Shift+B 手动收藏
document.addEventListener('keydown', function(e) {
if (e.ctrlKey && e.shiftKey && e.key === 'B') {
saveBookmark('manual');
alert('页面已收藏!');
}
});
})();
方法4:Python脚本(本地运行)
import json
import os
import webbrowser
from datetime import datetime
import sqlite3
class BookmarkManager:
def __init__(self, db_path='bookmarks.db'):
self.db_path = db_path
self.init_database()
def init_database(self):
"""初始化数据库"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS bookmarks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
url TEXT NOT NULL,
description TEXT,
tags TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
category TEXT DEFAULT '未分类'
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL
)
''')
conn.commit()
conn.close()
def add_bookmark(self, title, url, description='', tags=''):
"""添加书签"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO bookmarks (title, url, description, tags)
VALUES (?, ?, ?, ?)
''', (title, url, description, tags))
conn.commit()
conn.close()
print(f"已收藏: {title}")
def list_bookmarks(self, category=None, tag=None):
"""列出书签"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
query = "SELECT * FROM bookmarks"
params = []
if category:
query += " WHERE category = ?"
params.append(category)
if tag:
query += " WHERE tags LIKE ?" if 'WHERE' not in query else " AND tags LIKE ?"
params.append(f'%{tag}%')
query += " ORDER BY created_at DESC"
cursor.execute(query, params)
bookmarks = cursor.fetchall()
conn.close()
return bookmarks
def export_to_html(self, filename='bookmarks.html'):
"""导出为HTML书签文件"""
bookmarks = self.list_bookmarks()
html = '''<!DOCTYPE html>
<html>
<head>我的书签</title>
<meta charset="UTF-8">
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
.bookmark { margin: 10px 0; padding: 10px; border: 1px solid #ddd; }
.bookmark a { color: #0066cc; text-decoration: none; }
.bookmark a:hover { text-decoration: underline; }
.timestamp { color: #666; font-size: 0.8em; }
</style>
</head>
<body>
<h1>我的书签</h1>
<p>共 ''' + str(len(bookmarks)) + ''' 个书签</p>
'''
for b in bookmarks:
html += f'''
<div class="bookmark">
<a href="{b[2]}">{b[1]}</a>
<div class="timestamp">收藏于: {b[5]}</div>
</div>
'''
html += '''
</body>
</html>'''
with open(filename, 'w', encoding='utf-8') as f:
f.write(html)
print(f"已导出到 {filename}")
# 使用示例
if __name__ == "__main__":
manager = BookmarkManager()
# 添加书签
manager.add_bookmark(
"Google",
"https://www.google.com",
"搜索引擎",
"搜索,工具"
)
# 列出所有书签
bookmarks = manager.list_bookmarks()
for b in bookmarks:
print(f"{b[1]} - {b[2]}")
# 导出为HTML
manager.export_to_html()
使用方法
书签脚本:
- 创建一个新书签
- 将脚本代码粘贴到URL字段
- 点击书签即可收藏
浏览器扩展:
- 创建扩展文件夹
- 放入manifest.json和相关文件
- 在Chrome中加载已解压的扩展
Tampermonkey脚本:
- 安装Tampermonkey扩展
- 创建新脚本
- 复制粘贴代码并保存
Python脚本:
- 安装Python
- 运行脚本:
python bookmark_manager.py
功能特点
- ✅ 自动收藏访问的网页
- ✅ 支持快捷键操作
- ✅ 本地存储,无需服务器
- ✅ 支持导出为HTML
- ✅ 搜索和分类功能
- ✅ 跨平台兼容
选择适合你需求的方案,或者告诉我需要特定功能的调整!