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

泄露秘密 提交于 2019-12-11 18:59:19

问题


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

回答1:


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



回答2:


soup.find returns only the first one match, so you need soup.findAll. As for pretty print, you can use pprint.



来源:https://stackoverflow.com/questions/17648913/python-printing-to-a-key-pair-value-from-a-website-using-beautifulsoup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!