Created
June 5, 2010 14:48
-
-
Save jdelacueva/426674 to your computer and use it in GitHub Desktop.
Extracción norma de la web del BOE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
""" | |
Script para obtener la estructura de una norma jurídica o su | |
contenido desde la web del Boletín Oficial del Estado. | |
Ayuda: | |
------ | |
$ python extraer_norma.py -h | |
$ python extraer_norma.py --help | |
Extraer la estructura de una norma: | |
----------------------------------- | |
$ python extraer_norma.py -u URL | |
Extraer todo el contenido de una norma: | |
--------------------------------------- | |
$ python extraer_norma.py -u URL -t | |
$ python extraer_norma.py -u URL --todo | |
Guardar resultado en un archivo de texto: | |
----------------------------------------- | |
$ python extraer_norma.py -u URL > archivo.txt | |
$ python extraer_norma.py -u URL -t > archivo.txt | |
""" | |
__author__ = 'Javier de la Cueva' | |
__author_email__ = '[email protected]' | |
__copyright__ = 'AGPL v3' | |
import sys | |
from optparse import OptionParser | |
from lxml.html import parse | |
# Un ejemplo de url: | |
# LEY 15/2007, de 3 de julio, de Defensa de la Competencia. | |
# url = 'http://boe.es/aeboe/consultas/bases_datos/doc.php?id=BOE-A-2007-12946' | |
def main(): | |
usage = "usage: %prog -u url [-t]" | |
parser = OptionParser(usage=usage, version="%prog 0.1") | |
parser.add_option("-u", "--url", action="store", type="string", | |
dest="url", help="url de la norma en la pagina web del BOE") | |
parser.add_option("-t", action="store_true", dest="todo", | |
help="Imprimir toda la norma: estructura y articulos") | |
(options, args) = parser.parse_args() | |
if options.url: | |
url=options.url | |
try: | |
tree = parse(url).getroot() | |
except: | |
print "Error en URL" | |
sys.exit(0) | |
def extract_tree(tree): | |
for item in tree: | |
print item.text.encode('utf-8') | |
norma_tree = tree.xpath("//*[@class='documento-tit']|//p[@class='libro_num']|//p[@class='libro_tit']|//p[@class='titulo_num']|//p[@class='titulo_tit']|//p[@class='capitulo_num']|//p[@class='capitulo_tit']|//p[@class='seccion']|//p[@class='articulo']") | |
norma_arts = tree.xpath("//*[@class='documento-tit']|//p[@class='libro_num']|//p[@class='libro_tit']|//p[@class='titulo_num']|//p[@class='titulo_tit']|//p[@class='capitulo_num']|//p[@class='capitulo_tit']|//p[@class='seccion']|//p[@class='articulo']/following-sibling::*") | |
if options.todo: | |
extract_tree(norma_arts) | |
else: | |
extract_tree(norma_tree) | |
else: | |
print __doc__ | |
sys.exit(0) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment