Извлечение текста из вложенных тегов в XML с использованием BeautifulSoup в Python - PullRequest
2 голосов
/ 22 ноября 2011

Я пытаюсь извлечь текст из вложенных тегов, например, 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

, тогда на консоли будет выдано None для тегов заголовков, имеющих теги, перед извлечениемтеги.

1 Ответ

1 голос
/ 22 ноября 2011

Из 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.contents или tag.text:

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