· 5 years ago · Dec 12, 2020, 12:18 AM
1import requests
2import json
3import os
4import time
5
6requestsph = 0 # requests per hour
7start = time.time()
8
9
10def requestcheck(requests=requestsph, start=start):
11 if time.time() < start+3600:
12 requests += 1
13 if requests >= 950:
14 time.sleep(start+3600-time.time())
15 else:
16 start += 3600
17 requests = 0
18 return requests, start
19
20
21year = '2020'
22month = '12'
23day = '10'
24
25url = 'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos'
26
27param = dict(earth_date=str(year)+'-'+str(month)+'-'+str(day),
28 api_key='cBQ84BGIAgLZRwAiOyelY1z8F3YgFjemnXHi1QT6')
29images = []
30# api abfragen
31print('API-Request from %s...' % (url))
32data = requests.get(url=url, params=param)
33requestsph, start = requestcheck()
34jsondata = data.json()
35
36# bildlinks in liste speicher
37for key in jsondata['photos']:
38 images.append(key['img_src'])
39# Bilder herunterladen
40for img_link in images:
41 print('Downloading image %s...' % (img_link))
42 image = requests.get(img_link)
43 requestsph, start = requestcheck()
44 try:
45 image.raise_for_status()
46 if image.ok:
47 print('Downloaded successfully!')
48 except Exception as exc:
49 print('There was a Problem downloading file %s:\n%s' % (img_link, exc))
50 # speichern
51 date = year+'_'+month+'_'+day
52 fileName = 'C:\\Users\\Paul\\Desktop\\Python\\MarsRoverPics\\Images\\' + \
53 date+'_'+os.path.basename(img_link) # pfad ggf. anpassen
54 imgFile = open(fileName, 'wb')
55 for chunk in image.iter_content(100000):
56 imgFile.write(chunk)
57 imgFile.close()
58 print('Successfully saved image as: %s\n\n' % (fileName))
59