首页 > 解决方案 > Python Flask:用户下载抓取的图像

问题描述

我有一个小脚本,它是一个图像抓取工具。本质上,您为脚本提供了一个链接,它将网页上的所有图像下载到您桌面上的一个文件夹中。我想要相同的功能,但在浏览器上。我让用户输入链接,然后脚本开始将图像从链接下载到他们的计算机。我的代码如下:

@app.route('/')
def main():
   return render_template('index.html')

@app.route('/Downlading', methods=['POST'])
def Downlading():
   url= request.form['url']
   start = request.form['start']
   end = request.form['end']
   dphy = image_downloader(url) #this is the script that saves the images
   return str(dphy)

我能够获取用户 url 并将其传递给 image_downloader,它会下载图像。问题是图像是从命令提示符下载的。我希望脚本在浏览器中运行,就像在我的 IDE 中运行一样。对不起,如果这令人困惑。

我的 HTML 代码:

    <form action="/Downlading" method="POST" >
        URL: <input type="text" name="url"><br/>
        Start: <input type="text" name="start"><br/>
        End: <input type="text" name="end"><br/>
        <input type="submit" name="form" value="Submit" />

    </form>

标签: pythonflaskdownload

解决方案


您需要为要反映的变量创建一个 HTML 模板。例如:

HTML - 上传.html:

<html>
<title>Example on StackOverflow</title>
<p> The str representation of the variable dphy is {{ dphy }} </p>
</html>

Python(将其添加到现有的烧瓶脚本):

@app.route('/Downlading', methods=['POST'])
def Downlading():
   url= request.form['url']
   start = request.form['start']
   end = request.form['end']
   dphy = image_downloader(url) #this is the script that saves the images
   return render_template('upload.html', dphy=str(dphy))

这应该有效,但我现在无法测试它,所以我不是肯定的。这是通过 Flask 传递变量的基本思想——创建一个使用变量的模板,然后在渲染创建的模板时显式传递它。


推荐阅读