【发布时间】: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