我只有一个页面的源代码。
tree = etree.HTML(source_page_text)
image_list = tree.xpath('//img[@src]')
通过使用 xpath,我可以找到所有具有上述“src”属性的“img”标签。但是图像大小的信息在 css 中。在javascript中,我可以通过使用例如轻松找到大小
document.querySelectorAll("img")[83].height
因为它是一个对象。
那么如何在 python 中找到图像的大小?
最佳答案
由于您是在服务器上而不是在浏览器中,因此您必须(重新)下载图像并使用像 PIL 这样的库来获取它的大小。
from PIL import Image
import urllib.request
import io
def image_size(url)
with urllib.request.urlopen(url) as u:
f = io.BytesIO(u.read())
img = Image.open(f)
return img.size # (width, height) tuple
注意:您需要 PIL(pillow fork)库安装在您的系统上。
另一种选择是下载样式表并使用像tinycss 这样的解析器。尝试将 css 规则与选择器相关联以得出大小。不过,我认为这会很棘手。
关于python - 在 python 中有什么方法可以在 html 中找到图像的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44800736/