使用python中的BeautifulSoup从XML中的嵌套标签中提取文本

时间:2011-11-22 06:35:28

标签: python xml-parsing beautifulsoup

我试图从嵌套标签中提取文本,例如xml的格式为:

<thread id = 1_1>
  <post id = 1>
    <title>
      <ne>MediaPortal</ne> Install Guide
    </title>
    <content>
      <ne>MediaPortal</ne> Install Guide 0. Introduction and pre-requisites 
      <ne>MediaPortal</ne> is an open-source and free full-fledged <ne>HTPC</ne>
      front-end. It does everything you can ask for in a media center: video 
      playback, music playback, photo viewing, weather, TV tuning and recording, 
      etc. It has wide community support and thanks to it's excellent plug-in 
      and  skinning framework, there are lots of community-developed extensions 
      you can  pick and choose to make it your own. It is far more configurable 
      than <ne>Windows Media Center</ne>, and it works out-of-the-box with the 
      <ne>MCE</ne> remote. And because it provides so much more configuration 
      some find it a daunting task to install and configure. Therefore, this 
      guide will help alleviate some of that burden and help get a 
      <ne>MediaPortal</ne> installation up &amp; running. This guide is not 
      intended to replace the wonderful <ne>MediaPortal</ne> documentation, but 
      rather to introduce the AVS community to <ne>MediaPortal</ne> and provide
      a quick and easy set-up guide. If you need more details on configuration
    </content>
  </post>
</thread>

我需要在标签中提取数据并将其保存在单独的文件中。我能够做到这一点,然后我从美丽的汤对象中提取标签。现在,我想从和标签中提取文本并将其放在单独的文件中。请提出一些建议如何实现。

如果我做了

,则从汤品中提取标签
for title in soup.find('title')
   print title.string

然后在控制台上为提取标签前的标签标签提供无。

1 个答案:

答案 0 :(得分:1)

来自BeautifulSoup文档:

For your convenience, if a tag has only one child node,
and that child node is a string,the child node is made
available as tag.string, as well as tag.contents[0].

但是,在你的情况下:

>>> t = soup.find('title')
<title><ne>MediaPortal</ne> Install Guide</title>

因此,在您的情况下,您无法使用tag.string。但是,您仍然可以使用tag.contentstag.text

>>> t.contents
[<ne>MediaPortal</ne>, u' Install Guide']
>>> t.text
u'MediaPortalInstall Guide'