Weather script for Pythonista

I was traveling this past summer in Bar Harbor MA (beautiful place to visit), and the campgrounds we were staying at only had 1x data service for Verizon. Luckily I had a python script that would scrape weather.gov. Most of the weather apps failed because of timeout issues. I had to bump the timeout for the web request up to 2 minutes. But it worked for what we needed and let us know if we needed jackets for our hikes.


import os
import requests
import location
from bs4 import BeautifulSoup

server = ‘http://forecast.weather.gov/MapClick.php?lat=LAT_NUM&lon=LONG_NUM

try:

#print('Getting location')
#location.start_updates()
#loc_dict = location.get_location()
#location.stop_updates()


# recommend using hard coded GPS to save battery
#server = server.replace('LAT_NUM',str(loc_dict['latitude']))
#server = server.replace('LONG_NUM',str(loc_dict['longitude']))

# comment out these lines if using divice GPS and uncomment previous lines
server = server.replace('LAT_NUM', '44.352462')
server = server.replace('LONG_NUM', '-68.225340')


print('Getting weather data')
initial_request_reply = requests.get(server, timeout=120)


# throw error if not 200(ok) response code
if initial_request_reply.status_code!=200:
	initial_request_reply.raise_for_status()


print('Converting data')
web_data = BeautifulSoup(initial_request_reply.text, "html.parser")

print()
print()


# print where data is from
data = web_data.find_all('h2', class_='panel-title')
# element 0 is usually current conditions location
print(data[0].text.strip())

# print current conditions
data = web_data.find(id='current_conditions-summary').findAll('p')
for c in data:
	if c.attrs['class'][0].upper()!='MYFORECAST-CURRENT-SM':
		print(c.text.strip())

data = list(web_data.find(id='current_conditions_detail').findAll('td'))
for c in range(0,len(data),2):
	if data[c].text.strip().upper()=='BAROMETER':
		continue
	if data[c].text.strip().upper()=='DEWPOINT':
		continue
	print(data[c].text.strip() + ' - ' + data[c+1].text.strip())



data = web_data.find(id='detailed-forecast-body').findAll('div')

counter = 1
for line in data:
	child = line.findAll('div')
	if len(child)==2:
		print('-'*40)
		print(child[0].text.strip() + ' - ' + child[1].text.strip())
		counter += 1
		
	# change this number if you want forecast further out
	if counter>=6:
		break

except Exception as inst:
print(’-’*40)
print(type(inst)) # the exception instance
print()
for arg in inst.args:
print(arg)
print()
print(’-’*40)

print(’\n\nDone’)