如何编写可用Python脚本提取Google Chrome访问URL至TXT文件?
Got it, let's tackle this Chrome history to TXT problem—this is actually a common task once you know where Chrome stores its data and how to safely access it. I'll start with the Python solution since you preferred that, then follow up with a Java option.
Chrome stores your browsing history in a SQLite database file. The biggest pitfall people hit is that Chrome locks this file while running, so we'll first make a copy of the database to avoid permission errors. This script uses only standard libraries, so no extra installs needed.
import sqlite3 import shutil import os def chrome_history_to_txt(output_path="chrome_history_urls.txt"): # Detect Chrome history path based on OS if os.name == 'nt': # Windows history_path = os.path.expanduser(r'~\AppData\Local\Google\Chrome\User Data\Default\History') elif os.name == 'posix': # Mac/Linux mac_path = os.path.expanduser('~/Library/Application Support/Google/Chrome/Default/History') history_path = mac_path if os.path.exists(mac_path) else os.path.expanduser('~/.config/google-chrome/Default/History') else: raise OSError("Unsupported operating system") # Copy history database to temp file to avoid Chrome's lock temp_db = "temp_chrome_history.db" try: shutil.copy2(history_path, temp_db) except PermissionError: print("❌ Error: Chrome is running! Please close Chrome first and try again.") return # Connect to temp database and extract URLs conn = sqlite3.connect(temp_db) cursor = conn.cursor() # Fetch URLs sorted by most recent visit (remove ORDER BY if you don't need this) cursor.execute("SELECT url FROM urls ORDER BY last_visit_time DESC") urls = [row[0] for row in cursor.fetchall()] # Write URLs to TXT with UTF-8 encoding (handles special characters) with open(output_path, 'w', encoding='utf-8-sig') as txt_file: for url in urls: txt_file.write(f"{url}\n") # Cleanup conn.close() os.remove(temp_db) print(f"✅ Success! Saved {len(urls)} URLs to {output_path}") if __name__ == "__main__": chrome_history_to_txt()
How to use:
- Close Chrome completely (check task manager/activity monitor to make sure no background processes are running)
- Run the script—It’ll automatically detect your OS, copy the history database, extract URLs, and save them to
chrome_history_urls.txtin the same folder.
If you need a Java implementation, we’ll use the SQLite JDBC driver to connect to the history database. You’ll need to add the driver dependency first.
Maven Dependency (add to pom.xml):
<dependency> <groupId>org.xerial</groupId> <artifactId>sqlite-jdbc</artifactId> <version>3.45.2.0</version> </dependency>
Java Code:
import java.io.*; import java.sql.*; import java.nio.file.Files; import java.nio.file.Paths; public class ChromeHistoryExporter { public static void main(String[] args) { String outputFile = "chrome_history_urls.txt"; String historyDbPath = getChromeHistoryPath(); if (historyDbPath == null) { System.err.println("❌ Unsupported operating system or Chrome not found."); return; } String tempDbPath = "temp_chrome_history.db"; try { // Copy history database to avoid Chrome's lock Files.copy(Paths.get(historyDbPath), Paths.get(tempDbPath), java.nio.file.StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { System.err.println("❌ Error copying history file: " + e.getMessage()); System.err.println("Make sure Chrome is closed and you have proper file permissions."); return; } // Initialize resources Connection conn = null; Statement stmt = null; ResultSet rs = null; BufferedWriter writer = null; try { // Connect to SQLite temp database conn = DriverManager.getConnection("jdbc:sqlite:" + tempDbPath); stmt = conn.createStatement(); String query = "SELECT url FROM urls ORDER BY last_visit_time DESC"; rs = stmt.executeQuery(query); // Write URLs to TXT file with UTF-8 encoding writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); int urlCount = 0; while (rs.next()) { String url = rs.getString("url"); writer.write(url); writer.newLine(); urlCount++; } System.out.println("✅ Success! Saved " + urlCount + " URLs to " + outputFile); } catch (SQLException | IOException e) { e.printStackTrace(); } finally { // Cleanup resources try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); if (writer != null) writer.close(); Files.deleteIfExists(Paths.get(tempDbPath)); } catch (IOException | SQLException e) { e.printStackTrace(); } } } // Detect Chrome history path based on OS private static String getChromeHistoryPath() { String os = System.getProperty("os.name").toLowerCase(); if (os.contains("win")) { return System.getProperty("user.home") + "\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History"; } else if (os.contains("mac")) { return System.getProperty("user.home") + "/Library/Application Support/Google/Chrome/Default/History"; } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) { return System.getProperty("user.home") + "/.config/google-chrome/Default/History"; } else { return null; } } }
- Close Chrome First: Chrome locks the History database while running—you’ll get permission errors if you skip this step.
- Multiple Profiles: If you use Chrome with multiple profiles, the history path will be under
User Data/Profile 1,Profile 2, etc., instead ofDefault. Adjust the path in the code accordingly. - Incognito Mode: URLs from private/incognito browsing are not stored in this database—this only exports regular browsing history.
- Encoding: Using UTF-8 (or UTF-8-SIG for Python on Windows) ensures special characters and non-English URLs are saved correctly.
内容的提问来源于stack exchange,提问作者dan

