【问题标题】:Downloading Image Data URIs from Webpages via BeautifulSoup通过 BeautifulSoup 从网页下载图像数据 URI
【发布时间】:2015-07-27 19:58:43
【问题描述】:

我需要使用 Python 从网站检索图像。但是,图像不是链接文件的形式,而是 GIF 数据 URI。如何下载并将其存储在 .gif 文件中?

【问题讨论】:

  • 提供一个你正在尝试的例子。
  • @Ross,我无法提供该网页的 URL,因为它很敏感,但是:考虑:
  • 你可以发布一些没有 URL 的 Python 代码
  • 所以,我想使用 python 连接到这个 URL,并将图像下载为 .gif 文件。
  • @nivixzixer 我还没有编写任何代码,因为我不知道如何处理这个问题。

标签: python python-2.7 beautifulsoup


【解决方案1】:

这应该会让你朝着正确的方向前进。

首先,我假设您已检索到图像 uri 数据并将其保存在名为 img_data 的 python 变量中:

# Example
img_data = 'data:image/jpeg;base64,/9j/4A...<lots of data>...k='

现在您需要从 base64 解码图片并将其保存到文件中:

import base64

# Separate the metadata from the image data
head, data = img_data.split(',', 1)

# Get the file extension (gif, jpeg, png)
file_ext = head.split(';')[0].split('/')[1]

# Decode the image data
plain_data = base64.b64decode(data)

# Write the image to a file
with open('image.' + file_ext, 'wb') as f:
    f.write(plain_data)

【讨论】:

  • 完美运行。谢谢!
猜你喜欢
  • 2020-08-02
  • 1970-01-01
  • 2016-09-06
  • 2018-01-29
  • 2019-11-25
  • 1970-01-01
  • 1970-01-01
  • 2017-12-29
  • 1970-01-01
相关资源
最近更新 更多