#!/usr/bin/env python
	
from BeautifulSoup import BeautifulSoup
import urllib2

# Enable this if you get the following error:
# ascii' codec can't encode character 'x' in position y: ordinal not in range(128)
# ---
#import codecs
#import sys
#streamWriter = codecs.lookup('utf-8')[-1]
#sys.stdout = streamWriter(sys.stdout)

posten = "http://sporing.posten.no/sporing/KMSporingslink.aspx?PackageNumber=%s"
page = urllib2.urlopen(posten % pkg)
parser = BeautifulSoup(page)
	
# we only care about the last section
table = parser.findAll('table')[-1]
	
# print headers
print "%-9s %-6s %-25s %-15s" % ("Dato", "Tid", "Hendelse", "Poststed")
	
# the first table row is empty, skip it
for tr in table.findAll('tr')[1:]:
	
	# get table cells and strip whitespace
	# we use contents[0] instead of string because the last
	# column includes url's we don't need
	td = [td.contents[0].strip() for td in tr.findAll('td')]
	
	#finally, print
	print "%-9s %-6s %-25s %-15s" % (td[0], td[1], td[2], td[3])

