【问题标题】:Updating image text programmatically以编程方式更新图像文本
【发布时间】:2015-03-27 16:32:23
【问题描述】:

我犯了一个错误,并在我的网络服务器上重命名了一些图像。这破坏了我的 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 中的图像 src,以添加当前 HTML 文件的父文件夹,直到根文件夹。

我认为我上面的内容应该非常接近,我只是缺少一点 Python 知识。

这需要考虑很多,所以我会为此提供赏金以奖励最佳答案。谢谢:)

【问题讨论】:

  • 对不起,变量mf是什么?在第 12 行使用它之前似乎没有定义它。这可能是一个错字,你的意思是f?

标签: python html python-2.7 parsing beautifulsoup


【解决方案1】:

以下是我可能会做的事情。重点是更新soup对象,然后写出来。我在进行更改的地方添加了 cmets。第一部分是一样的。

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 文件。这些用“替代想法”表示。

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))

【讨论】:

  • 您还可以使用正则表达式将反斜杠字符替换为下划线。
猜你喜欢
  • 2015-11-20
  • 2011-04-18
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2015-08-11
  • 1970-01-01
  • 1970-01-01
  • 2021-01-14
相关资源
最近更新 更多