-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapiRequests.py
68 lines (48 loc) · 1.92 KB
/
apiRequests.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
# This scripts handles the retrival part of the api
################ IMPORTS ####################
from pypexels import PyPexels
import requests
import os
##############################################
global search_urls
search_urls = list()
############# main ###########################
# function that retrieves list of all urls from api from a giving string
def execute_search(key, string, pages, format, progress_function):
if (len(search_urls) > 0):
search_urls.clear()
pexels_instance = PyPexels(api_key=key)
search_results = pexels_instance.search(query=string, per_page=pages)
progress_function(0)
while True:
for image in search_results.entries:
search_urls.append(image.src.get(format))
print(image.src.get(format))
if not search_results.has_next:
break
search_results = search_results.get_next_page()
progress_function('finished')
#function that downloads images on a certain path
def download_images(urls, path_, download_amount, progress_function):
path = path_
if (len(path.split('./')) == 1):
path = './' + path
if (path[len(path)-1] != '/'):
path = path + '/'
print(path)
if not os.path.exists(path):
os.makedirs(path)
for url in urls:
count = (urls.index(url) + 1)
segment = (len(url.split('/')) - 1)
img_name = path + url.split('/')[segment].split('?')[0]
if (count <= download_amount):
porcentage = int((count*100)/(download_amount))
progress_function(porcentage, count, download_amount)
img = requests.get(url).content
if not os.path.exists(img_name):
with open(img_name, 'wb') as image:
image.write(img)
print(img_name, ' has been downloaded sucessfully!')
print('All downloads completed!')
###############################################