2012-08-03 13 views
13

que necesito para obtener el texto dentro de los dos elementos en una cadena:análisis de HTML para obtener el texto dentro de un elemento

source_code = """<span class="UserName"><a href="#">Martin Elias</a></span>""" 

>>> text 
'Martin Elias' 

¿Cómo podría lograr esto?

+0

Theres varias maneras de pelar el gato aquí. ¿Cuál es el resultado final? Podría hacer javascript o algún análisis del lado del servidor. –

Respuesta

26

busqué "pitón analizar HTML" y este fue el primer resultado: https://docs.python.org/2/library/htmlparser.html

Este código se toma de los documentos pitón

from HTMLParser import HTMLParser 

    # create a subclass and override the handler methods 
    class MyHTMLParser(HTMLParser): 
     def handle_starttag(self, tag, attrs): 
      print "Encountered a start tag:", tag 
     def handle_endtag(self, tag): 
      print "Encountered an end tag :", tag 
     def handle_data(self, data): 
      print "Encountered some data :", data 

    # instantiate the parser and fed it some HTML 
    parser = MyHTMLParser() 
    parser.feed('<html><head><title>Test</title></head>' 
       '<body><h1>Parse me!</h1></body></html>') 

aquí está el resultado:

Encountered a start tag: html 
Encountered a start tag: head 
Encountered a start tag: title 
Encountered some data : Test 
Encountered an end tag : title 
Encountered an end tag : head 
Encountered a start tag: body 
Encountered a start tag: h1 
Encountered some data : Parse me! 
Encountered an end tag : h1 
Encountered an end tag : body 
Encountered an end tag : html 

Usando esto y mirando el código en HTMLParser, se me ocurrió esto:

class myhtmlparser(HTMLParser): 
    def __init__(self): 
     self.reset() 
     self.NEWTAGS = [] 
     self.NEWATTRS = [] 
     self.HTMLDATA = [] 
    def handle_starttag(self, tag, attrs): 
     self.NEWTAGS.append(tag) 
     self.NEWATTRS.append(attrs) 
    def handle_data(self, data): 
     self.HTMLDATA.append(data) 
    def clean(self): 
     self.NEWTAGS = [] 
     self.NEWATTRS = [] 
     self.HTMLDATA = [] 

Se puede utilizar la siguiente manera:

from HTMLParser import HTMLParser 

pstring = source_code = """<span class="UserName"><a href="#">Martin Elias</a></span>""" 


class myhtmlparser(HTMLParser): 
    def __init__(self): 
     self.reset() 
     self.NEWTAGS = [] 
     self.NEWATTRS = [] 
     self.HTMLDATA = [] 
    def handle_starttag(self, tag, attrs): 
     self.NEWTAGS.append(tag) 
     self.NEWATTRS.append(attrs) 
    def handle_data(self, data): 
     self.HTMLDATA.append(data) 
    def clean(self): 
     self.NEWTAGS = [] 
     self.NEWATTRS = [] 
     self.HTMLDATA = [] 

parser = myhtmlparser() 
parser.feed(pstring) 

# Extract data from parser 
tags = parser.NEWTAGS 
attrs = parser.NEWATTRS 
data = parser.HTMLDATA 

# Clean the parser 
parser.clean() 

# Print out our data 
print tags 
print attrs 
print data 

Ahora usted debería ser capaz de extraer los datos desde esas listas fácilmente. Espero que esto haya ayudado!

+0

Esto es hermoso :) – AsheKetchum

18

Recomiendo usar la biblioteca Python Beautiful Soup 4.

pip install beautifulsoup4 

Hace que el análisis de HTML sea realmente sencillo.

from bs4 import BeautifulSoup 
source_code = """<span class="UserName"><a href="#">Martin Elias</a></span>""" 
soup = BeautifulSoup(source_code) 
print soup.a.string 
>>> 'Martin Elias' 
+0

Sé que la pregunta está etiquetada python-2.x, pero creo que debe tenerse en cuenta que beautifulsoup solo funciona en python 2.x. – LJNielsenDk

+3

Beautiful Soup 4 funciona tanto en 2.7 como en 3. –

+0

¿Dónde encuentras buena documentación de la API para sopa hermosa? –

0

También puede intentar usar html5lib y XPath, there is a good question about it here, esa respuesta tiene un detalle importante (namespaceHTMLElements) para recordar a hacer html5lib comportarse como se esperaba. Perdí tanto tiempo intentando ponerlo a funcionar porque pasé por alto que tenía que cambiar eso.

2

Instalar BeautifulSoup y Se puede hacer así:

from BeautifulSoup import BeautifulSoup 
source_code = '"""<span class="UserName"><a href="#">Martin Elias</a></span>"""' 
soup = BeautifulSoup(source_code) 
print soup.find('span',{'class':'UserName'}).text 
Cuestiones relacionadas