You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows环境下如何通过Python程序控制Google Chrome导入或导出书签

Hey there! Let's figure out how to automate Chrome bookmark import/export on Windows using Python. I've got three solid approaches for you, each with its own pros and cons depending on your needs:

方法1:直接操作Chrome的本地书签文件(最高效)

Chrome stores your bookmarks in a JSON file by default—no need to run Chrome or simulate clicks, just handle the file directly. The catch? You need to close Chrome first, since it locks the file while running.

导出书签

You can either back up the raw JSON file or convert it to the standard HTML bookmark format that Chrome uses for exports:

import json
import os
from datetime import datetime

# Path to Chrome's bookmarks file (Windows default)
bookmarks_path = os.path.expandvars(r"%LOCALAPPDATA%\Google\Chrome\User Data\Default\Bookmarks")

# Step 1: Backup the raw JSON bookmark data
with open(bookmarks_path, 'r', encoding='utf-8') as f:
    bookmarks_data = json.load(f)

backup_filename = f"chrome_bookmarks_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
with open(backup_filename, 'w', encoding='utf-8') as f:
    json.dump(bookmarks_data, f, indent=2, ensure_ascii=False)

print(f"Raw JSON backup saved to {backup_filename}")

# Step 2: Convert and export as Chrome-compatible HTML
def traverse_bookmarks(node, html_lines):
    if 'children' in node:
        for item in node['children']:
            if item['type'] == 'folder':
                html_lines.append(f"<DT><H3>{item['name']}</H3>")
                html_lines.append("<DL><p>")
                traverse_bookmarks(item, html_lines)
                html_lines.append("</DL><p>")
            elif item['type'] == 'url':
                html_lines.append(f"<DT><A HREF=\"{item['url']}\">{item['name']}</A>")

# Build HTML structure
html_content = [
    "<!DOCTYPE NETSCAPE-Bookmark-file-1>",
    "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">",
    "<TITLE>Bookmarks</TITLE>",
    "<H1>Bookmarks</H1>",
    "<DL><p>"
]

# Include bookmarks from all Chrome folders (bar, other, synced)
traverse_bookmarks(bookmarks_data['roots']['bookmark_bar'], html_content)
traverse_bookmarks(bookmarks_data['roots']['other'], html_content)
traverse_bookmarks(bookmarks_data['roots']['synced'], html_content)

html_content.append("</DL><p>")

# Save HTML file
html_filename = f"chrome_bookmarks_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
with open(html_filename, 'w', encoding='utf-8') as f:
    f.write('\n'.join(html_content))

print(f"HTML export saved to {html_filename}")

导入书签

To import, you can either replace the JSON file with a backup, or parse an HTML bookmark file and merge it into Chrome's JSON structure:

import json
import os
from datetime import datetime
from bs4 import BeautifulSoup

# First, close Chrome to release the file lock
os.system("taskkill /im chrome.exe /f 2>nul")

# Paths for import
import_html_path = "your_exported_bookmarks.html"  # Replace with your file
bookmarks_path = os.path.expandvars(r"%LOCALAPPDATA%\Google\Chrome\User Data\Default\Bookmarks")

# Load existing bookmark data
with open(bookmarks_path, 'r', encoding='utf-8') as f:
    bookmarks_data = json.load(f)

# Parse HTML bookmarks and add to Chrome's structure
def parse_html_bookmarks(soup, parent_folder):
    for dt_tag in soup.find_all('dt'):
        # Handle folders
        folder_name = dt_tag.find('h3')
        if folder_name:
            new_folder = {
                "date_added": str(int(datetime.now().timestamp() * 1e6)),
                "date_modified": str(int(datetime.now().timestamp() * 1e6)),
                "name": folder_name.get_text(strip=True),
                "type": "folder",
                "children": []
            }
            parent_folder['children'].append(new_folder)
            # Recursively parse sub-folders
            sub_dl = dt_tag.find_next_sibling('dl')
            if sub_dl:
                parse_html_bookmarks(sub_dl, new_folder)
        
        # Handle individual bookmarks
        bookmark_link = dt_tag.find('a')
        if bookmark_link:
            new_bookmark = {
                "date_added": str(int(datetime.now().timestamp() * 1e6)),
                "guid": os.urandom(16).hex(),
                "id": str(int(datetime.now().timestamp() * 1000)),
                "name": bookmark_link.get_text(strip=True),
                "type": "url",
                "url": bookmark_link['href']
            }
            parent_folder['children'].append(new_bookmark)

# Load and parse the HTML file
with open(import_html_path, 'r', encoding='utf-8') as f:
    soup = BeautifulSoup(f, 'html.parser')

# Import into the "Other Bookmarks" folder (change to 'bookmark_bar' for the main bar)
parse_html_bookmarks(soup.find('dl'), bookmarks_data['roots']['other'])

# Save the updated bookmark data back to Chrome's file
with open(bookmarks_path, 'w', encoding='utf-8') as f:
    json.dump(bookmarks_data, f, indent=2, ensure_ascii=False)

print("Bookmarks imported successfully! Restart Chrome to see changes.")

Note: You'll need to install BeautifulSoup for the HTML parsing: pip install beautifulsoup4

方法2:使用Chrome DevTools Protocol(CDP)控制运行中的Chrome

If you need to work with a running Chrome instance, CDP lets you communicate directly with Chrome via a websocket—no GUI simulation required.

First, launch Chrome with remote debugging enabled:

chrome.exe --remote-debugging-port=9222

Then use Python to send commands:

import json
import websockets
import asyncio

async def export_bookmarks_via_cdp():
    # Connect to Chrome's remote debugging endpoint
    async with websockets.connect("ws://localhost:9222/devtools/browser") as ws:
        # Send command to fetch the full bookmark tree
        await ws.send(json.dumps({
            "id": 1,
            "method": "Bookmarks.getTree"
        }))
        response = await ws.recv()
        response_data = json.loads(response)
        
        if 'result' in response_data:
            bookmarks_tree = response_data['result']['tree']
            # Save the raw bookmark data
            with open("cdp_bookmarks_export.json", 'w', encoding='utf-8') as f:
                json.dump(bookmarks_tree, f, indent=2, ensure_ascii=False)
            print("Bookmarks exported via CDP successfully!")

asyncio.run(export_bookmarks_via_cdp())

For importing, you can use the Bookmarks.add method from the CDP API. Install the required library first: pip install websockets

方法3:Selenium + PyAutoGUI(模拟GUI操作)

This method mimics manual clicks and keyboard shortcuts, which is useful if you need to see the GUI action. It's less stable than the other methods, though, since it depends on Chrome's UI layout.

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time
import pyautogui

# Launch Chrome
driver = webdriver.Chrome()

# Open the bookmark manager
driver.get("chrome://bookmarks/")
time.sleep(1)  # Wait for the page to load

# Trigger the export dialog with Ctrl+Shift+O (Windows shortcut)
ActionChains(driver)\
    .key_down(Keys.CONTROL)\
    .key_down(Keys.SHIFT)\
    .send_keys('o')\
    .key_up(Keys.SHIFT)\
    .key_up(Keys.CONTROL)\
    .perform()

time.sleep(1)  # Wait for the save dialog to appear

# Use PyAutoGUI to type the save path and confirm
pyautogui.typewrite("C:\\Users\\YourUsername\\Desktop\\chrome_bookmarks.html")
pyautogui.press('enter')

time.sleep(2)
driver.quit()

Note: Install dependencies first: pip install selenium pyautogui. You'll also need to download a ChromeDriver matching your Chrome version.


内容的提问来源于stack exchange,提问作者vy32

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:55:22