my Python code throws an Error after a short period of 5 to 7 requests or so called "File "c:/Users/xxx/Desktop/Webscraper.py", line 15, in programm zeit=(webseite["data"]).
KeyError: 'data'
Why does it throw this error ? The key always should be there.
import requests
import time
import os
def programm():
while True:
url=f"https://api.nanopool.org/v1/eth/network/timetonextepoch"
webseite = requests.get(url).json()
zeit=(webseite['data'])
puffer=int(420)
while zeit > puffer:
url=f"https://api.nanopool.org/v1/eth/network/timetonextepoch"
webseite = requests.get(url).json()
zeit=(webseite["data"])
puffer=int (420)
print("Zeit zum DAG-Wechsel in Sekunden:",zeit)
time.sleep(60) #Refresh Zeit
while zeit < puffer:
print("Neustart in",int(zeit)) # Zeit zur nächsten DAG Epoche in Sekunden
os.startfile("C:/Users/xxxx/Desktop/restart1.bat")
print("restart")
time.sleep(5000)
break
break
while True:
programm()
break
CodePudding user response:
Websites can fail intermittently for many reasons. Perhaps you make too many requests or the server is overloaded or its down for maintenance. Your code should check error codes which will help find out what goes wrong.
Since you want to keep trying, you could just add that into your code. I've extracted the data gathering into a separate function that only returns when it gets good stuff. This reduces repetition in your code.
import requests
import time
import os
def get_nanopool_time_to_next_epoch():
while True:
url=f"https://api.nanopool.org/v1/eth/network/timetonextepoch"
resp = requests.get(url)
if resp.status_code >= 300:
print("--------------------------------------------")
print("Http error", resp.status_code)
print(resp.content)
webseite = requests.get(url).json()
if 'data' not in webseite:
print("--------------------------------------------")
print("'data' not in result")
print(resp.content)
else:
return webseite['data']
time.sleep(1)
def programm():
while True:
zeit = get_nanopool_time_to_next_epoch()
puffer=int(420)
while zeit > puffer:
zeit = get_nanopool_time_to_next_epoch()
puffer=int (420)
print("Zeit zum DAG-Wechsel in Sekunden:",zeit)
time.sleep(60) #Refresh Zeit
while zeit < puffer:
print("Neustart in",int(zeit)) # Zeit zur nächsten DAG Epoche in Sekunden
os.startfile("C:/Users/xxxx/Desktop/restart1.bat")
print("restart")
time.sleep(5000)
break
break
while True:
programm()
break