【发布时间】:2025-11-22 15:40:02
【问题描述】:
我想用 Flask 做一个网页,它可以让我根据一些关键字搜索图片,并在网页中返回两张相关的图片。
并且,假设关键字是“史蒂夫·乔布斯”,这些与“史蒂夫·乔布斯”相关的图片将被 Google 搜索抓取并存储在名为“史蒂夫·乔布斯”的文件中。
但我仍然无法显示文件中的图像并返回空白页。
你好.py
@app.route("/about",methods=['GET', 'POST'])
def about():
...
DIR = os.path.join(os.getcwd())
DIR = os.path.join(DIR, query.split()[0])
...
def show_index():
for i,(img,Type) in enumerate(ActualImages[:2]):
try:
req = urllib.request.Request(img, headers=header)
raw_img = urllib.request.urlopen(req).read()
cntr = len([i for i in os.listdir(DIR) if image_type in i]) + 1
print(cntr)
if len(Type)==0:
f = open(os.path.join(DIR,image_type + "_"+ str(cntr)+".jpg"),'wb')
else:
f = open(os.path.join(DIR,image_type + "_"+ str(cntr)+"."+Type),'wb')
f.write(raw_img)
f.close()
except Exception as e:
print('>>> Could not load: '+img)
print(e)
return f
return render_template('about.html', f = f)
关于.html
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<img src="{{f}}" alt="f">
</body>
</html>
【问题讨论】: