首页 > 解决方案 > 使用 Python 调整 HTML 中的图像大小 - 我该如何正确操作?

问题描述

我在 wordpress 帖子中嵌入了 10 张图片。我使用了 html,以便可以用 260px 的宽度替换它们最初的任何宽度(并且高度应该相应地缩放)。我还想把它们都对齐到右边,换行。

我所做的是将一些 html 复制到文本文件中:

<img class="alignright wp-image-3087" src="https://wordpress-346062-1147012.cloudwaysapps.com/wp-content/uploads/2020/02/Signature-Design-By-Ashley-coffee-table-300x159.jpg" alt="Signature Design By Ashley coffee table" width="300" height="159" />

目标宽度和高度:260 像素、138 像素。我知道它只需要基本的数学运算,所以我已经知道如何缩放图像。但我的问题在于改变weightand的值height。是否有用于存储和修改 img 属性的内置模块?

我已经想出了一个脚本来搜索和替换,但它是固定的。如果我有 800 或 1254 的宽度怎么办?我知道我不能只使用一些硬编码的检测器。

with open("unedited_html") as u:
    listofu = [line.rstrip('\n') for line in u]
unedited_html_contents = listofu[0]

infile = raw_input("Enter file name: ")
outfile = "resized_image_%s"%(infile)

checkWords = (old_dimensions) #not yet established, because this is unpredictable
repWords = (new_dimensions) #260, and whatever the height is

f1 = open(infile)
f2 = open(outfile,"w+")
for line in f1:
    for check, rep in zip(checkWords, repWords):
        line = line.replace(check, rep)
    f2.write(line)
f1.close()
f2.close()

标签: pythonhtmlcss

解决方案


解决了!我用了 BeautifulSoup 和 re。

from bs4 import BeautifulSoup
import re

infile = raw_input("Enter file name: ")
outfile = "resized_image_%s"%(infile)
outfile2 = 'resized_image_2_%s'%(infile)

f1 = open(infile)

for line in f1:
    if any(re.findall(r'<img', str(line), re.IGNORECASE)) == True:
        soup = BeautifulSoup(line)
        img = soup.img
        old_width = float(img['width'])
        old_height = float(img['height'])
        img['height'] = int(260*(old_height/old_width))
        img['width'] = 260
        with open(outfile,'a') as o:
            o.write(unicode(soup))
    else:
        with open(outfile,'a') as o:
            o.write(unicode(line))
f1.close()


f2 = open(outfile)
f3 = open(outfile2,"w+")
for line in f2:
    if any(re.findall(r'<img', str(line), re.IGNORECASE)) == True:
        y = re.sub(r'alignnone','alignright',line)
        f3.write(unicode(y))
    else:
        f3.write(unicode(line))
f2.close()
f3.close()

推荐阅读