import urllib2
from BeautifulSoup import BeautifulStoneSoup
class City:
"A simple container of arbitrary named attributes."
def __init__(self, **kw):
self.__dict__.update(kw)
def __repr__(self):
return str(self.__dict__)
def FetchCityLocations():
"""A Sampling of Location Information about Cities
An example of fetching XML representing information about a handful
of cities along with the state within which they reside and their
latitude/longitude.
"""
page = urllib2.urlopen("http://www.4dsolutions.net/ocn/python/cities.xml")
soup = BeautifulStoneSoup(page)
page.close()
cities = []
for city in soup.cities.findAll('city'):
c = City(
name=city['name'],
state=city['state'],
latitude="%s.%s%s" % (
city.lat['deg'], city.lat['min'], city.lat['dir']),
longitude="%s.%s%s" % (
city.long['deg'], city.long['min'], city.long['dir']),
)
cities.append(c)
return cities
cities = FetchCityLocations()
print cities Note(s):
- This example uses standard Python except for
[http://www.crummy.com/software/BeautifulSoup/ the BeautifulSoup package] which must be installed separately.
Here's a version which uses the built-in XML processing capabilities of Python:
import urllib, xml.dom.minidom
class City:
"A simple container of arbitrary named attributes."
def __init__(self, **kw):
self.__dict__.update(kw)
def __repr__(self):
return str(self.__dict__)
def FetchCityLocations():
"""A Sampling of Location Information about Cities
An example of fetching XML representing information about a handful
of cities along with the state within which they reside and their
latitude/longitude.
"""
f = urllib.urlopen("http://www.4dsolutions.net/ocn/python/cities.xml")
d = xml.dom.minidom.parse(f)
cities = []
for city in d.getElementsByTagName("city"):
attr = city.getAttribute
lat = city.getElementsByTagName("lat")[0]
long = city.getElementsByTagName("long")[0]
latAttr = lat.getAttribute
longAttr = long.getAttribute
cities.append(
City(
name=attr("name"),
state=attr("state"),
latitude="%s.%s%s" % (
latAttr("deg"), latAttr("min"), latAttr("dir")
),
longitude="%s.%s%s" % (
longAttr("deg"), longAttr("min"), longAttr("dir")
)
)
)
return cities
cities = FetchCityLocations()
print cities 