4

我有一些使用Xapi检索的快餐店的 OSM 数据,以下是一些示例结果:

<osm version="0.6" generator="Osmosis SNAPSHOT-r26564">
   <node id="486275964" version="4" timestamp="2010-05-03T08:21:42Z" uid="12055" user="aude" changeset="4592597" lat="38.8959533" lon="-77.0212458">
      <tag k="name" v="Potato Valley Cafe"/>
      <tag k="amenity" v="fast_food"/>
   </node>
   <node id="486275966" version="4" timestamp="2010-08-06T16:44:13Z" uid="207745" user="NE2" changeset="5418228" lat="38.8959399" lon="-77.0196338">
      <tag k="cuisine" v="burger"/>
      <tag k="name" v="McDonald's"/>
      <tag k="amenity" v="fast_food"/>
   </node>
   <node id="612190923" version="1" timestamp="2010-01-12T14:01:27Z" uid="111209" user="cov" changeset="3603297" lat="38.893683" lon="-77.0292732">
      <tag k="level" v="-1"/>
      <tag k="cuisine" v="sandwich"/>
      <tag k="name" v="Quizno's"/>
      <tag k="amenity" v="fast_food"/>
   </node> 
</osm>
<!--corrected indentation-->

我正在尝试在 python 中使用 BeautifulSoup 从中提取纬度、经度、名称和美食。我可以用这段代码得到经纬度没有问题:

soup = BeautifulSoup(results)
takeaways = soup.findAll('node')

for eachtakeaway in takeaways:
    longitude = str(eachtakeaway['lon'])
    lattitude = str(eachtakeaway['lat'])

但我不知道名字:

name = str(eachtakeaway['name'])

这引发了错误:

TypeError: 'NoneType' object is not callable

你能告诉我该怎么做吗?谢谢。

4

2 回答 2

6

问题是,方括号用于检索标签的属性,即latlon。但是,名称是另一个标签的属性。尝试这样的事情:

soup = BeautifulSoup(results)
takeaways = soup.findAll('node')

for eachtakeaway in takeaways:
    another_tag = eachtakeaway('tag')
    for tag_attrs in another_tag:
        if str(tag_attrs['k']) == 'cuisine':
            print str(tag_attrs['v'])

这将返回美食价值。相同的概念适用于检索name

*未经测试

于 2012-11-15T14:46:45.450 回答
2

<node>元素没有name属性。标签的子标签执行以下操作:

for eachtakeaway in takeaways:
    longitude = str(eachtakeaway['lon'])
    lattitude = str(eachtakeaway['lat'])
    nametag = eachtakeaway.find('tag', k='name')
    name = str(nametag['v']) if nametag is not None else ''

示范:

>>> takeaways = soup.findAll('node')
>>> for eachtakeaway in takeaways:
...     nametag = eachtakeaway.find('tag', k='name')
...     print str(nametag['v']) if nametag is not None else ''
... 
Potato Valley Cafe
McDonald's
Quizno's
于 2012-11-15T14:45:12.650 回答