x ai python change html image tag png 2026-06-25
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:
-
Install BeautifulSoup if you don't have it:
pip install beautifulsoup4 -
Save the script as
change_png_to_webp.py. -
Run it:
python change_png_to_webp.py
Features:
- Handles both
.pngand.PNG - Preserves the full path (e.g.,
i/cat.png→i/cat.webp) - Keeps all other attributes (
alt,width,height, etc.) - Safe: only modifies
srcattributes ending in.png - Overwrites the original file (you can modify it to save as a new file if preferred)
Would you like a version that:
- Saves to a new file instead of overwriting?
- Also updates any CSS background images?
- Processes multiple HTML files at once?
Just let me know!