gpt4 book ai didi

python - 在 Python 中从 Url 获取图像尺寸

转载 作者:行者123 更新时间:2023-11-28 19:37:22 25 4
gpt4 key购买 nike

我想获取网站上浏览者所看到的图像尺寸。

我正在使用漂亮的汤,我得到这样的图片链接:

links = soup.findAll('img', {"src":True})

我获取图像尺寸的方法是使用:

link.has_key('height')
height = link['height']

宽度也类似。但是,某些链接仅具有这些属性之一。我试过 PIL,但如果下载的话,它会给出实际的图像大小。

有没有其他方法可以找到网站上看到的图像尺寸?

最佳答案

您的主要问题是您正在搜索 html 源代码以查找对高度和宽度的引用。在大多数情况下(当事情做得很好时),图像没有在 html 中指定高度和宽度,在这种情况下,它们将以图像文件本身的高度和宽度呈现。

要获取图像文件的高度和宽度,您需要实际查询并加载该文件,然后使用图像处理检查高度和宽度。如果这是您想要的,请告诉我,我会帮助您完成该过程。

import urllib, cStringIO
from PIL import Image

# given an object called 'link'

SITE_URL = "http://www.targetsite.com"
URL = SITE_URL + link['src']
# Here's a sample url that works for demo purposes
# URL = "http://therealtomrose.therealrosefamily.com/wp-content/uploads/2012/08/headshot_tight.png"
file = cStringIO.StringIO(urllib.urlopen(URL).read())
im=Image.open(file)
width, height = im.size
if link.has_key('height'):
height = link['height'] # set height if site modifies it
if link.has_key('width'):
width = link['width'] # set width if site modifies it

要求:该方法需要PIL库进行图像处理。

# from command line in a virtual environment
pip install PIL

关于python - 在 Python 中从 Url 获取图像尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17864603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com