#!/usr/bin/python2 # -*- coding: utf-8 -*- from bs4 import BeautifulSoup import requests import json import os import time def tofloat(s, delim=" "): return float(s.split(delim)[0].replace(",", ".")) def pretty(value, unit, desc=""): d = {} d["value"] = tofloat(value) d["unit"] = unit d["desc"] = desc return d def getNew(): res = {} try: link = "http://www.wetterbaer.de/Daten/currenttm.html" fd = requests.get(link).text soup = BeautifulSoup(fd, 'html.parser') tr = soup.find("table").find_all("tr") d = tr[2].find_all("td")[2].get_text().strip() t = tr[3].find_all("td")[2].get_text().strip() res["timestamp"] = d + " " + t res["t_curr"] = pretty((tr[6].find_all("td")[2].find_all("font")[-1].get_text()), u"°C", "Current Temperature (+2m)") res["t_max"] = pretty(tr[6].find_all("td")[3].find_all("font")[-1].get_text(), u"°C", "Maximum Tempeature today (+2m)") res["t_min"] = pretty(tr[6].find_all("td")[4].find_all("font")[-1].get_text(), u"°C", "Minimum Tempeature today (+2m)") res["h_curr"] = pretty((tr[15].find_all("td")[2].find_all("font")[-1].get_text()), u"%", "Current Humidity") res["h_max"] = pretty(tr[15].find_all("td")[4].find_all("font")[-1].get_text(), u"%", "Maximum Humidity today") res["h_min"] = pretty(tr[15].find_all("td")[3].find_all("font")[-1].get_text(), u"%", "Minimum Humidity today") res["error"] = "No Error" except requests.exceptions.ConnectionError: res["error"] = "Error: Could not connect to " + link return res cache = "cache.json" timeout = 15*60 curr = None if not os.path.exists(cache) or (os.path.getmtime(cache) + timeout) < int(time.time()): # cache expired. getting new info curr = getNew() with open(cache, "w") as f: json.dump(curr, f) else: # cache valid. delivering old info with open(cache, "r") as f: curr = json.load(f) print json.dumps(curr)