-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
68 lines (47 loc) · 1.96 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen
import logging
from flask import Flask, render_template,request
# from pymongo.mongo_client import MongoClient
import os
app = Flask(__name__)
save_dir = "./static/images"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
# gives me all files inside any directory
def list_files(directory):
return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
@app.route('/')
def makingHomePage():
return render_template('index.html')
@app.route('/images', methods=['POST'])
def search_results():
if request.method == 'POST':
query = request.form['images']
if not os.path.exists(save_dir):
os.makedirs(save_dir)
response = requests.get(f"https://www.google.com/search?q={query}&sca_esv=587928711&rlz=1C1CHBF_enIN1048IN1048&tbm=isch&source=lnms&sa=X&ved=2ahUKEwit3pSZ0_eCAxVDyTgGHanECwMQ_AUoAnoECAMQBA&biw=798&bih=737&dpr=1")
soup = BeautifulSoup(response.content,'html.parser')
image_tags = soup.find_all('img')
len(image_tags)
del image_tags[0]
img_data_mongo = []
for i in image_tags:
image_url = i['src']
image_data = requests.get(image_url).content
mydict = {
"index":image_url,"image":image_data
}
img_data_mongo.append(mydict)
# save the images in directory
with open(os.path.join(save_dir,f"{query}_{image_tags.index(i)}.jpg"),"wb") as f:
f.write(image_data)
# here i want to get all files inside static/images directory
files_names = list_files("./static/images")
# for fn in files_names:
# print(fn)
return render_template('images.html',file_name=files_names)
if __name__ == '__main__':
# run() method of Flask class runs the application
# on the local development server.
app.run()