美丽的汤如何在迭代时打印标签

时间:2011-01-01 20:25:15

标签: python xml beautifulsoup

我的xml看起来像这样,我想获取位置。

<?xml version="1.0" encoding="UTF-8"?>
<playlist version="1" xmlns="http://xspf.org/ns/0/">
 <trackList>
  <track>
   <location>file:///home/ashu/Music/Collections/randomPicks/ipod%20on%20sep%2009/Coldplay-Sparks.mp3</location>
   <title>Coldplay-Sparks</title>
  </track>
  <track>
   <location>file:///home/ashu/Music/Collections/randomPicks/gud%201s/Coldplay%20Warning%20sign.mp3</location>
   <title>Coldplay Warning sign</title>
  </track>....

我在尝试:

from BeautifulSoup import BeautifulSoup as bs
soup = bs (the_above_xml_text)
for track in soup.tracklist:
    print track.location.string

但这不起作用,因为我得到了:

AttributeError: 'NavigableString' object has no attribute 'location'

如果能提前感谢,我怎样才能达到效果。

2 个答案:

答案 0 :(得分:1)

使用lxml,速度更快,支持xpath:

>>> doc = lxml.etree.fromstring(yourxml)
>>> doc.xpath('//n:location/text()', namespaces={'n': 'http://xspf.org/ns/0/'})
['file:///home/ashu/Music/Collections/randomPicks/ipod%20on%20sep%2009/Coldplay-Sparks.mp3',
'file:///home/ashu/Music/Collections/randomPicks/gud%201s/Coldplay%20Warning%20sign.mp3']

答案 1 :(得分:0)

您可以使用findAll

>>> for track in soup.findAll('track'):
...     print track.title.string
...     print track.location.string
... 
Coldplay-Sparks
file:///home/ashu/Music/Collections/randomPicks/ipod%20on%20sep%2009/Coldplay-Sparks.mp3
Coldplay Warning sign
file:///home/ashu/Music/Collections/randomPicks/gud%201s/Coldplay%20Warning%20sign.mp3