从网页下载图像数据的URI通过BeautifulSoup [英] Downloading Image Data URIs from Webpages via BeautifulSoup

查看:137
本文介绍了从网页下载图像数据的URI通过BeautifulSoup的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从使用Python网站获取的图像。然而,图像不是在链接文件的形式,但作为一个GIF数据的URI。怎样下载这个并将其存储在一个.gif文件?

I need to retrieve an image from a website using Python. However, the image is not in the form of a linked file, but as a GIF Data URI. How do I download this and store it in a .gif file?

推荐答案

这应该让你在正确的方向前进。

This should get you going in the correct direction.

首先,我会假设你已经检索到的图像数据的URI,它保存在一个Python变量称为img_data:

First, I'll assume you have retrieved the image uri data and it is saved in a python variable called img_data:

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

现在你需要去code从BASE64画面并将其保存到一个文件:

Now you'll need to decode the picture from base64 and save it to a file:

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)

这篇关于从网页下载图像数据的URI通过BeautifulSoup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆