-2

I need to change all images of a static website and provide WebP support. So every file-name.jpg file has file-name.webp alternative in the same folder.

I want to turn every

<img src="file-name.jpg" class="classnames" >

into

<picture>
  <source srcset="file-name.webp" type="image/webp">
  <img src="file-name.jpg" class="classnames" >
</picture> 

I don't want to manually change all the photos by going through all the pages one by one. Is there a way to bulk replace all existing elements while keeping all class and attributes?

aydgn
  • 167
  • 1
  • 8

1 Answers1

-1

I wrote a simple python script that does this work for you (I wrote it from my mobile, if you see some errors tell me).

import re, os

files = os.listdir()
for file in files:
    if file.endswith('html'):
        pattern = r'<img src="(.+)" class="(.+)" >'
        with open(file, 'r') as f:
            html = f.read()

        finds = re.findall(pattern, html)

        for f in finds:
            orCode = '<img src="' + f[0] + '" class="' + f[1] + '" >
            newCode = '<picture>\n <source srcset="' + f[0].split('.')[0] + '.webp" type="image/webp">\n<img src="' + f[0] + '" class="' + f[1] + '" >\n</picture>'
            html = html.replace(orCode, newCode)

        with open(file, 'w') as f:
            f.write(html)
Rom7x
  • 56
  • 1
  • 6
  • This seems designed to work only for one file. I need to run this multiple html files. – aydgn Mar 10 '22 at 09:59
  • I updated it now. Now you should put this script in the folder with all the html files. Warning: This will overwrite the old htmls so be careful and make a backup. – Rom7x Mar 11 '22 at 12:28