Fixing a few bugs in Python pywapi related to Canadian cities

While experimenting with the pywapi I found a few problems that require an article, in case someone is facing the same issues.

First, for Canadian cities, you need a more current version of pywapi. On Ubuntu 12.04, the python-pywapi is 0.2.2-1 and does not have the API for Weather.com. The version on 14.04 is 0.3.6, and does have that API.

Second, you need to find the code for your city. Here is a list of codes.

Third, you will get an error in the afternoons, since some elements will be empty for the mornings, and the program will try to parse them and abort doing so.

The error is:

Traceback (most recent call last):
  File "./weather.py", line 6, in 
    d = pywapi.get_weather_from_weather_com(loc_id)
  File "/path/to/pywapi.py", line 223, in get_weather_from_weather_com
    key2] = part.getElementsByTagName(tag2)[0].firstChild.data
AttributeError: 'NoneType' object has no attribute 'data'

To overcome this, go to around line 220 in the file, and find this snippet of code:

for tag2 in ('icon', 't', 'bt', 'ppcp', 'hmid'):
  key2 = key_map[tag2]
  tmp_forecast[time_of_day][
    key2] = part.getElementsByTagName(tag2)[0].firstChild.data

Change that to add a check on empty elements, like so:

for tag2 in ('icon', 't', 'bt', 'ppcp', 'hmid'):
  key2 = key_map[tag2]
  if part.getElementsByTagName(tag2)[0].firstChild  None:
    tmp_forecast[time_of_day][
      key2] = part.getElementsByTagName(tag2)[0].firstChild.data
  else:
     tmp_forecast[time_of_day][key2] = 'N/A'

While you are at it, change the Weather.com API URL to the current one.

Find this line:
WEATHER_COM_URL      = 'http://xml.weather.com/weather/local/%s?' + \

And change it to be as follows, which is the new location of the API for weather.com:

WEATHER_COM_URL      = 'http://wxdata.weather.com/wxdata/weather/local/%s?' + \

Once you do that, the API should work.

Contents: 

Tags: