lunes, 21 de febrero de 2011

Parsear XML con Python



Desde hace unas semanas estoy leyendo, estudiando y practicando Python. Es un lenguaje tan apasionante como interesante. En pocos días, me atrevería a decir que incluso horas, con unos conocimientos básicos de programación, puedes crear verdaderas maravillas pythonianas.
El caso es en la Asociación Comunidade O Zulo , hemos puesto en marcha un proyecto para customizar una distribución Ubuntu Linux y completarla con material multimedia. Para realización las aportaciones multimedia de este proyecto, todavía un embrión pero os adelanto que tiene muy buena pinta, hemos levantado un sitio web en Drupal dónde los usuarios podrán enviar las imágenes. [Explicación técnica que omito para no aburrir al personal] Para recuperar las imágenes estamos desarrollando un script en Python que lee el XML y vía SQLite completa un álbum en Shotwell. El script básico para parsear el XML es el siguiente:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# xml-parser-ozulo-0.0.1-dev.py
#
# Copyright 2011 Alberto Permuy Leal
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
import sys, urllib
from xml.etree import ElementTree as et


def main():
documento = et.parse(urllib.urlopen('http://www.comunidadeozulo.org/rss.xml')).getroot()
entradas = documento.getiterator('item')
for una_entrada in entradas:
elementos = una_entrada.getiterator()
for un_elemento in elementos:
if un_elemento.tag == 'title':
print un_elemento.text
return 0

if __name__ == '__main__':
main()

Es casi idéntico a esta entrada, salvo que he añadido el parse vía urllib.

No hay comentarios: