以编程方式更新图像文本

Updating image text programmatically

我犯了一个错误,在我的网络服务器上重命名了一些图像。这破坏了我 HTML 中的一堆图像源(大约 300 个文件......!)。不幸的是没有备份,所以这是我需要通过编程来解决的问题! :)

我之前的文件夹结构是这样的:

Root Folder
   >directory
     >subdirectory
        >img
          image1.gif
     >subdirectory2
        >img
          image1.gif
   >directory2
     >img
        image1.gif
    ...

我现在已经将所有图像提取到一个文件夹中,并将所有父文件夹的名称添加到图像名称的根文件夹之前,所以我们剩下:

directory_subdirectory_image1.gif
directory_subdirectory2_image1.gif
directory2_image1.gif

全部在一个文件夹中。

我想删除 "img/" 前缀并将所有文件夹的名称添加到我的图像 src 的根文件夹之前。

我试图使用 BeautifulSoup 来执行此操作,获取所有图像,我无法获取此 运行 将父文件夹添加到根文件夹之前:

import os
from bs4 import BeautifulSoup

do = dir_with_original_files = 'C:\Users\ADMIN\Desktop\RootFolder'
dm = dir_with_modified_files = 'C:\Users\ADMIN\Desktop\RootFolderNewImgSrc'

for root, dirs, files in os.walk(do):
    for f in files:
        if f.endswith('~'): #you don't want to process backups
            continue
        original_file = os.path.join(root, f)
        modified_file = os.path.join(dm, mf)
        with open(original_file, 'r') as orig_f, \
            open(modified_file, 'w') as modi_f:
            soup = BeautifulSoup(orig_f.read())
            for t in soup.find_all('img'):
              #not sure what to do here - how do I edit the image source to prepend all parent directories?
            # This is where you create your new modified file.
            modi_f.write(soup.prettify().encode(soup.original_encoding)) 

我只是希望有人能帮我编辑这个 (一)运行! (b) HTML 文件仅 运行 (c) 更新我的 HTML 中的图像 srcs 以将当前 HTML 文件的父文件夹添加到根文件夹之前。

我想我上面的内容应该很接近,我只是缺少了一点 Python 知识。

要吸收的东西太多了,所以我会为此悬赏以奖励最佳答案。谢谢:)

以下是我可能会怎么做。重点是更新soup对象,然后写出来。我在进行更改的地方添加了评论。第一部分相同。

import os
from bs4 import BeautifulSoup

do = dir_with_original_files = 'C:\Users\ADMIN\Desktop\RootFolder'
dm = dir_with_modified_files = 'C:\Users\ADMIN\Desktop\RootFolderNewImgSrc'

首先,如果我理解正确的话,您只想处理 HTML 个文件,所以我更改了第一个 for 循环中的条件以反映这一点。其次,我不知道 Windows 上 Python 路径的所有来龙去脉(我假设您使用的是 Windows 机器),所以我在某些地方给出了代码变体。

我有一个替代想法,将旧的 HTML 文件写入修改后的目录,然后覆盖现有的 HTML 文件。这些用 "Alternate idea."

表示
for root, dirs, files in os.walk(do):
    for f in files:
        if not f.endswith('.html'): # only work with .html files
            continue
        original_file = os.path.join(root, f)
        modified_file = os.path.join(dm, f)
        with open(original_file, 'r') as orig_f:
            soup = BeautifulSoup(orig_f)

#       Alternative idea: write old files to dm
#       Make a backup copy in modified files dir
#       with open(modified_file, 'w') as modi_f:
#           modi_f.write(soup.prettify().encode(soup.original_encoding))

        for t in soup.find_all('img'):                    # Note: soup exists outside of with
            try:
                old_src = t['src']                        # Access src attribute
                image = os.path.split(old_src)[1]         # Get file name
#               Variant:
#               image = old_src.replace('img/','')
                relpath = os.path.relpath(root, do)       # Get relative path from do to root
#               Variant:
#               relpath = root[len(do):]
                folders = relpath.strip('\').split('\') # Remove outer slashes, split on folder separator
                new_src = '_'.join(folders.append(image)) # Join folders and image by underscore
                t['src'] = new_src                        # Modify src attribute
            except:                                       # Do nothing if tag does not have src attribute
                pass
        with open(modified_file, 'w') as modi_f:
            modi_f.write(soup.prettify().encode(soup.original_encoding)) 

#       Alternative idea: overwrite original html files
#       with open(original_file, 'w') as orig_f:
#           orig_f.write(soup.prettify().encode(soup.original_encoding))