Search code examples
pythonpretty-print

python printing to a key pair value from a website using beautifulsoup


I have this code extracted using beautifulsoup from this website https://api.projectnimbus.org/neaodataservice.svc/NowcastSet ?

After displaying all the location how do I pretty print it to a key pair value ? Like Location : Ang Mo Kio Latitude : 1.3546846 Longitude : 103.564132 ?

from BeautifulSoup import BeautifulStoneSoup #Using bs3
import urllib2

url="https://api.projectnimbus.org/neaodataservice.svc/NowcastSet"
request = urllib2.Request(url)
request.add_header("accept", "*/*")
request.add_header('AccountKey', "OSJeROQjTg4v7Ec3kiecjw==")
request.add_header('UniqueUserID', "00000000000000000000000000000001")
result = urllib2.urlopen(request)
xml_str = result.read()

soup = BeautifulStoneSoup(xml_str)

prop_list = []
for content in soup.findAll("m:properties"):
    props = {}
    for prop in content.findChildren():
        props[prop.name[2:]] = prop.text
    prop_list.append(props)

print prop_list

Solution

  • Modified:

    import urllib2
    from BeautifulSoup import BeautifulStoneSoup #Using bs3
    
    url="https://api.projectnimbus.org/neaodataservice.svc/NowcastSet"
    request = urllib2.Request(url)
    request.add_header("accept", "*/*")
    request.add_header('AccountKey', "OSJeROQjTg4v7Ec3kiecjw==")
    request.add_header('UniqueUserID', "00000000000000000000000000000001")
    result = urllib2.urlopen(request)
    xml_str = result.read()
    
    soup = BeautifulStoneSoup(xml_str)
    
    prop_list = []
    for content in soup.findAll("m:properties"):
        props = {}
        for prop in content.findChildren():
            props[prop.name[2:]] = prop.text
        prop_list.append(props)
    
    for prop in prop_list:
        print "Area: %(area)s\nLat: %(latitude)s\nLong: %(longitude)s\n" % prop