2012-11-15 123 views
3

我已經得到了我使用Xapi檢索快餐店一些OSM數據,並here是一些示例結果:BeautifulSoup發現XML標籤

<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--> 

我試圖用BeautifulSoup在Python中提取拉特,長,名稱和美食。我可以用這個代碼得到lat和長沒有問題:

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

的問題是,在方括號檢索標籤,即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

*未經測試

+0

bs4有一個xml模式。圍繞爲什麼要使用XML模式,在這樣一個實例任何想法? – kalu

+1

@kalu我BS4的經驗是有限的,但我在BS4 XML模式支持XML命名空間,區分大小寫標籤處理等XML的細節的印象是。我不能保證這一點,因爲我只從朋友/同事交談圖紙,也沒有研究此事。 – That1Guy

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