'How to bulk replace <img> element to <picture>?
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?
Solution 1:[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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
