Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 美丽的汤如何打印一个标签,而在它上面迭代_Python_Xml_Beautifulsoup - Fatal编程技术网

Python 美丽的汤如何打印一个标签,而在它上面迭代

Python 美丽的汤如何打印一个标签,而在它上面迭代,python,xml,beautifulsoup,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/Cold

我的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>....
但这不起作用,因为我得到:

AttributeError:'navigablesting'对象没有属性'location'
如何实现结果,提前感谢。

使用,速度更快,支持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']

您可以使用
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

是的,为了简洁起见我选了那个部分你想让我全部展示吗?是的。还要解释“不工作”是什么意思。findAll是否使用某种模式匹配?使用findAll似乎破坏了结构化数据库的整体意义document@Bunny:学习XPath足以解决80%的问题只需30分钟。nosklo,谢谢你的建议,我会防御性地学习,但可能在下个周末:P
>>> 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