【问题标题】:Beatifulsoup: how to get image size by urlBeautifulsoup:如何通过 url 获取图像大小
【发布时间】:2018-06-30 17:03:13
【问题描述】:

如果提取的图像 url,我需要获取宽度和高度,我使用 get('width'),但这似乎不起作用

description = soup.find("div", id="module_product_detail")
img= description.find("img")
print(img.get('width'))

输出为无。 链接是这样的

<img alt="image" src="https://bos1.lightake.net:20011/UploadFiles/ShopSkus/1000x1000/Y2463/Y246302/sku_Y246302_1.jpg"/>

【问题讨论】:

  • img 标签中没有width 属性
  • 有没有办法通过只有url来获取宽度和高度?

标签: python beautifulsoup


【解决方案1】:

由于没有 width 和 height 属性,访问图像元数据的唯一方法是下载它并像这样读取它:

from requests import get
from io import BytesIO
from PIL import Image


image_raw = get('https://upload.wikimedia.org/wikipedia/commons/3/30/Googlelogo.png')
image = Image.open(BytesIO(image_raw.content))
width, height = image.size

print(width, height)

# Output:
# 1368 469

【讨论】:

  • get is not defined,除了 Pillow 模块,我应该安装其他东西吗?
  • get 来自requests 你导入了from requests import get 吗?
  • 您还需要安装requests module
  • 我已经导入了整个请求模块,并且之前在脚本中用于检索 url
  • 好的,你也可以import requests,如果你愿意,可以requests.get() :-)
猜你喜欢
  • 2014-06-08
  • 2012-05-19
  • 2013-02-28
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-21
  • 1970-01-01
相关资源
最近更新 更多