【发布时间】:2018-12-26 01:54:57
【问题描述】:
我正在尝试根据此线程从 html 文件中保存图像 How do I extract images from html files in a directory?
import os, os.path
from PIL import Image
from bs4 import BeautifulSoup as bs
path = 'c:/Users/Desktop/html/'
for root, dirs, files in os.walk(path):
for f in files:
soup = bs(open(os.path.join(root, f)), 'lxml')
for image in soup.find_all("img"):
image = image.get('src')
alt = image.get('alt')
im = Image.open(os.path.join(root, image))
im.save(path+image+alt, "png")
print(os.path.join(root, image))
Content of the html file
<!DOCTYPE html>
<html>
<body>
<img src="images/1.jpg" alt="Image1Name">
</body>
</html>
图片的完整文件路径是
c:/Users/Desktop/html/images/1.jpg 之后 c:/Users/Desktop/html/images/Image1Name.png
我看过这些主题: Using a variable as a Save file name ~ im.save(type, '.png') Modify path name when saving with PIL
错误
soup = bs(open(os.path.join(root, f)), 'lxml') init 中的文件“C:\Python\Python36-32\lib\site-packages\bs4__init__.py”,第 191 行 标记 = 标记.read() 解码中的文件“C:\Python\Python36-32\lib\encodings\cp1252.py”,第 23 行 返回 codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError:“charmap”编解码器无法解码位置 77 中的字节 0x81:字符映射到
如何正确使用 alt 描述保存和重命名 html 文件中的图像?
【问题讨论】:
标签: python image save python-imaging-library