【问题标题】:Python - PIL Save & Rename Image From HTML file Using alt DescriptionPython - PIL 使用 alt 描述从 HTML 文件中保存和重命名图像
【发布时间】: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


    【解决方案1】:

    我没有遇到您的编码问题,所以我无能为力。

    不过,为了提供帮助,我会将 im.save(path+image+alt, "png") 更改为 im.save(os.path.join(path, os.path.dirname(image), alt+' .png'))

    • 用 os.path.join 替换 + 符号只是为了提高通用性 处理
    • 用 os.path.dirname(image) 替换 image 是因为你 不想要'images/1.jpg',你想要'images'
    • 将“.png”添加到 alt 是 因为您可能想将文件命名为“Image1Name.png” 比'Image1Name'。之后,“png”的第二个参数不是 需要。

    另外,你的代码 -

    for image in soup.find_all("img"):
        image = image.get('src')
        alt = image.get('alt')
    

    有问题。 "image = image.get('src')" 将 "image" 更改为字符串,这意味着 "image.get('alt')" 将出现错误。我会推荐 -

    for img in soup.find_all("img"):
        image = img.get('src')
        alt = img.get('alt')
    

    【讨论】:

    • 非常感谢您的建议 - 虽然我仍然收到错误消息,但我不介意。它重命名图像 - 再次感谢您! :)
    猜你喜欢
    • 2012-12-01
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 2017-06-15
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    相关资源
    最近更新 更多