如何在python文件中返回图像?为了姜

2024-06-26 14:00:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码

import json
from goose import Goose

def extract(url):
    g = Goose()
    article = g.extract(url=url)
    if article.top_image is None:
        return "none" 
    else:
        if article.top_image.src is None:
          return "none"
        else:
            resposne = {'image':article.top_image.src}
            return article.top_image.src

这里我想返回图像文件,而不是“无”。为了上传图像文件,我需要在静态文件中保存图像并将其作为图像返回吗?我一直在用html从静态文件中返回图像,但我不确定如何使用python实现,或者有其他方法吗?在


Tags: 图像imageimportsrcnoneurlreturnif
1条回答
网友
1楼 · 发布于 2024-06-26 14:00:36

您在article.top_image.src中有图像资源的URL,因此只需下载图像并将其返回即可。您可以将^{}模块用于下载部分:

import requests

def extract(url):
    article = Goose().extract(url)
    if article.top_image is None or article.top_image.src is None
        return "none"

    r = requests.get(article.top_image.src)
    return r.content

这将从函数返回实际的图像数据。在

您可能希望将该图像作为HTTP响应返回,在这种情况下,您可以从视图函数返回:

^{pr2}$

相关问题 更多 >