SoFunction
Updated on 2025-04-25

Python script implementation to delete Google Chrome history

Preface

In this article, you will learn to write a Python program that will use user input as keywords, such as Amazon, Geek Blog, etc. Then search for this keyword in your Google Chrome history, and if you find this keyword in any URL, it will delete it.

For example, if you typed the keyword 'geeksforgeeks', it would search your Google Chrome history, like 'www . geekforgeks . org', and it's obvious that the URL contains the keyword 'geeksforgeeks', it would delete it, and it would search for articles (like 'geeksforgeeks' is a good portal for preparing for competitive programming interviews?') The title contains "geeksforgeeks" and delete it. First, get the location of Google Chrome history files in your system.

Notice:

The location of Google Chrome history files in Windows is generally: C:\ Users\manishkc\AppData\Local\Google\Chrome\User Data\Default\History.

Complete code

import sqlite3

# establish the connection with
# history database file which is 
# located at given location
# you can search in your system 
# for that location and provide 
# the path here
conn = ("/path/to/History")

# point out at the cursor
c = ()

# create a variable id 
# and assign 0 initially
id = 0  

# create a variable result 
# initially as True, it will
# be used to run while loop
result = True

# create a while loop and put
# result as our condition
while result:

    result = False

    # a list which is empty at first,
    # this is where all the urls will
    # be stored
    ids = []

    # we will go through our database and 
    # search for the given keyword
    for rows in ("SELECT id,url FROM urls\
    WHERE url LIKE '%geeksforgeeks%'"):

        # this is just to check all
        # the urls that are being deleted
        print(rows)

        # we are first selecting the id
        id = rows[0]

        # append in ids which was initially
        # empty with the id of the selected url
        ((id,))

    # execute many command which is delete
    # from urls (this is the table)
    # where id is ids (list having all the urls)
    ('DELETE from urls WHERE id = ?',ids)

    # commit the changes
    ()

# close the connection 
()

Output:

(16886, '/')

Method supplement

Clean up cache and data in Chrome browser using Python

Implementation ideas

Cleaning up the cache and data of Chrome browser mainly involves the following steps:

  • Find the user data directory of Chrome browser.
  • Delete or clear relevant cache and data files.
  • Ensure the security of operations and avoid accidentally deleting important user data.

1. Find Chrome's user data directory

Chrome's user data directory is usually located in the following path:

Windows: C:\Users\<username>\AppData\Local\Google\Chrome\User Data
macOS: /Users/<username>/Library/Application Support/Google/Chrome
Linux: /home/<username>/.config/google-chrome

2. Delete cache and data files

In the user data directory, caches and other files can be found. Typically, cache files are stored in the Default/Cache and Default/Media Cache directories. We can use Python's os library and shutil library to perform file operations.

3. Implement code examples

Here is a simple Python example that demonstrates how to clean up caches in Chrome:

import os
import shutil
import platform

# Determine the user data directorydef get_chrome_user_data_path():
    system = ()
    if system == "Windows":
        return (('LOCALAPPDATA'), 'Google', 'Chrome', 'User Data', 'Default')
    elif system == "Darwin":  # macOS
        return (('~'), 'Library', 'Application Support', 'Google', 'Chrome', 'Default')
    elif system == "Linux":
        return (('~'), '.config', 'google-chrome', 'Default')
    else:
        raise Exception("Unsupported operating system")

# Clean the cachedef clear_chrome_cache():
    user_data_path = get_chrome_user_data_path()
    cache_path = (user_data_path, 'Cache')
    media_cache_path = (user_data_path, 'Media Cache')
    
    # Check whether the cache directory exists and delete it    if (cache_path):
        (cache_path)
        print("Cleaning the cache is complete!")
    else:
        print("The cache directory does not exist.")

    if (media_cache_path):
        (media_cache_path)
        print("Cleaning the media cache is done!")
    else:
        print("The media cache directory does not exist.")

if __name__ == "__main__":
    clear_chrome_cache()

Code parsing

First, use () to get the operating system type, so that the user data directory can be dynamically set.

Build the path to cache and media cache.

Use the () method to delete the specified directory and its contents to complete the cache cleaning.

Things to note

Backup data: Before performing a cleanup operation, please make sure to back up important browsing data to avoid mistaken deletion.

Close Chrome: When cleaning up the cache, make sure the Chrome browser is closed to prevent the file from being used and cannot be deleted.

Guide to clearing Chrome caches with Python

Steps to clear Chrome cache

Step 1: Find the Chrome Cache Directory

On Windows systems, Chrome's cache is usually located in the following directory:

C:\Users\<Your Username>\AppData\Local\Google\Chrome\User Data\Default\Cache

In macOS systems, it is usually located at:

/Users/<Your Username>/Library/Caches/Google/Chrome/Default

Step 2: Write Python code to clear the cache

Using Python to delete these cached files can automate this process and greatly improve efficiency. Here is a code example that demonstrates how to clear Chrome cache using Python:

import os
import shutil
import platform

def clear_chrome_cache():
    # Get the current system's platform    system = ()
    
    if system == 'Windows':
        cache_path = (['LOCALAPPDATA'], r'Google\Chrome\User Data\Default\Cache')
    elif system == 'Darwin':  # macOS
        cache_path = (['HOME'], 'Library/Caches/Google/Chrome/Default')
    else:  # Other operating systems        print(f"Unsupported OS: {system}")
        return

    try:
        # Clear the cache directory        if (cache_path):
            (cache_path)
            (cache_path)  # Recreate the cache directory            print("Chrome cache cleared successfully.")
        else:
            print("Cache directory does not exist.")
    except Exception as e:
        print(f"Error occurred while clearing cache: {e}")

if __name__ == "__main__":
    clear_chrome_cache()

Code parsing

Platform detection: Use the () function to judge the current operating system to determine the cache path.

Path building: build the path to Chrome cache based on the operating system.

Delete and Rebuild: Use () to delete the cache directory and use () to recreate an empty cache directory.

Exception handling: Catch and handle any possible errors to ensure the program runs stably.

This is the article about deleting Google Chrome history in Python scripts. For more related content related to Python browser deletion, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!