x ai python change html image tag png 2026-06-25

By Xah Lee. Date: .

ai answer

write a python script, define function change_png_to_webp(file_path), open a html page, find image links to png, e.g. <img src="i/cat.png" alt="cat" width="715" height="699" /> change the link to to cat.webp

Here's the Python script with the requested function:

import os
from bs4 import BeautifulSoup

def change_png_to_webp(file_path):
    """
    Opens an HTML file, finds all <img> tags where src ends with .png,
    changes the extension to .webp, and overwrites the file with the updated HTML.

    Returns True if changes were made, False otherwise.
    """
    if not os.path.exists(file_path):
        print(f"Error: File not found: {file_path}")
        return False

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

    modified = False

    # Find all <img> tags and update PNG sources
    for img in soup.find_all('img'):
        if 'src' in img.attrs:
            src = img['src']
            if src.lower().endswith('.png'):
                # Replace .png with .webp (preserves the rest of the path/filename)
                new_src = src[:-4] + '.webp'
                img['src'] = new_src
                print(f"Changed: {src}{new_src}")
                modified = True

    if modified:
        # Write back the modified HTML
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(str(soup))
        print(f"✅ Successfully updated {file_path}")
        return True
    else:
        print("ℹ️ No .png images found in the HTML.")
        return False

# Example usage
if __name__ == "__main__":
    # Change this to your HTML file path
    html_file = "index.html"   # ← update this
    change_png_to_webp(html_file)

How to use it:

  1. Install BeautifulSoup if you don't have it:

    pip install beautifulsoup4
  2. Save the script as change_png_to_webp.py.

  3. Run it:

    python change_png_to_webp.py

Features:

Would you like a version that:

Just let me know!