-
Notifications
You must be signed in to change notification settings - Fork 1
/
convert.py
42 lines (34 loc) · 1.34 KB
/
convert.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import os
import sys
from bs4 import BeautifulSoup
def replace_img_urls(directory, old_host, new_host):
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.html'):
file_path = os.path.join(root, file)
with open(file_path, 'r') as f:
soup = BeautifulSoup(f, 'html.parser')
img_tags = soup.find_all('img')
for img_tag in img_tags:
if img_tag.has_attr('src'):
src = img_tag['src']
if src.startswith(old_host):
img_tag['src'] = new_host + src[len(old_host):]
elif src.startswith('/'):
img_tag['src'] = new_host + src[1:]
if img_tag.has_attr('data-srcset'):
src = img_tag['data-srcset']
if src.startswith(old_host):
img_tag['data-srcset'] = new_host + src[len(old_host):]
elif src.startswith('/'):
img_tag['data-srcset'] = new_host + src[1:]
with open(file_path, 'w') as output_file:
output_file.write(str(soup))
if __name__ == '__main__':
if len(sys.argv) < 4:
print("Usage: python3 convert.py <directory> <old_host> <new_host>")
sys.exit(1)
directory = sys.argv[1]
old_host = sys.argv[2]
new_host = sys.argv[3]
replace_img_urls(directory, old_host, new_host)