python - 使用 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 像素。我知道它只需要基本的数学运算,所以我已经知道如何缩放图像。但我的问题在于改变weight
and的值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()
解决方案
解决了!我用了 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()
推荐阅读
- python - 在类中创建和声明列表
- c# - C# 在 For 循环中按值更改变量名
- c# - 静态字段没有改变?
- c++ - Linux 中的未知类型名称 uint64_t 和 uint16_t uint8_t
- apache-spark - 对 Spark/Graphx/Pregel 示例程序的停止条件感到困惑,以查找“路径距离”
- nativescript - Nativescript Playground:未捕获的错误消息
- bash - 通过 SSH 访问 codeship 上的 github repo
- python - Python 请求:多部分,其中一部分为 json
- javascript - 如何在 window.alert() 中显示无序列表?
- java - jOOQ 在预期 UTC 时使用本地时区设置时间戳