2009-02-28 19 views
6

¿Cómo puedo eliminar todo el código HTML de una cadena en Python? Por ejemplo, ¿cómo puedo convertir:Eliminación de HTML de Python

blah blah <a href="blah">link</a> 

en

blah blah link 

Gracias!

+0

Podría ser exagerado para sus propósitos, pero pruebe BeautifulSoup si sus cadenas tienen HTML más complicado o malformado. Advertencia: no creo que esté disponible para Python 3.0 todavía. – bernie

Respuesta

7

Se puede utilizar una expresión regular para eliminar todas las etiquetas:

>>> import re 
>>> s = 'blah blah <a href="blah">link</a>' 
>>> re.sub('<[^>]*>', '', s) 
'blah blah link' 
+0

Puede simplificar su expresión regular a '<.*?>', lo que logrará los mismos resultados, pero esto supone HTML con formato correcto, como lo hace el suyo. – UnkwnTech

+0

¿Tiene que verificar por citado>, o no están permitidos? ¿Puedes tener o algo así? –

+0

@Unkwntech: Prefiero <[^>] *> más de <.*?> ya que el primero no necesita seguir el rastreo para encontrar el final de la etiqueta. –

0
>>> import re 
>>> s = 'blah blah <a href="blah">link</a>' 
>>> q = re.compile(r'<.*?>', re.IGNORECASE) 
>>> re.sub(q, '', s) 
'blah blah link' 
18

Cuando su solución de expresión regular golpea una pared, prueba este programa muy fácil (y confiable) BeautifulSoup.

from BeautifulSoup import BeautifulSoup 

html = "<a> Keep me </a>" 
soup = BeautifulSoup(html) 

text_parts = soup.findAll(text=True) 
text = ''.join(text_parts) 
+0

BeautifulSoup golpea la misma pared también. Ver http://stackoverflow.com/questions/598817/python-html-removal/600471#600471 – jfs

10

También hay una pequeña biblioteca llamada stripogram que puede ser utilizado para despojar algunas o todas las etiquetas HTML.

Se puede utilizar la siguiente manera:

from stripogram import html2text, html2safehtml 
# Only allow <b>, <a>, <i>, <br>, and <p> tags 
clean_html = html2safehtml(original_html,valid_tags=("b", "a", "i", "br", "p")) 
# Don't process <img> tags, just strip them out. Use an indent of 4 spaces 
# and a page that's 80 characters wide. 
text = html2text(original_html,ignore_tags=("img",),indent_width=4,page_width=80) 

Así que si quieres simplemente tira a todo el HTML, se pasa valid_tags (=) a la primera función.

Puede encontrar el documentation here.

2

html2text hará algo como esto.

+0

html2text es ideal para producir resultados legibles y formateados sin un paso adicional. Si todas las cadenas HTML que necesita convertir son tan simples como su ejemplo, entonces BeautifulSoup es el camino a seguir. Si es más complejo, html2text hace un gran trabajo para preservar el intento legible del original. –

5

regexs, BeautifulSoup, html2text no funcionan si un atributo tiene '>' en ella. Ver Is “>” (U+003E GREATER-THAN SIGN) allowed inside an html-element attribute value?

'solución basada en parser' HTML/XML podría ayudar en estos casos, por ejemplo, stripogramsuggested by @MrTopf funciona.

Aquí es ElementTree solución basada en:

####from xml.etree import ElementTree as etree # stdlib 
from lxml import etree 

str_ = 'blah blah <a href="blah">link</a> END' 
root = etree.fromstring('<html>%s</html>' % str_) 
print ''.join(root.itertext()) # lxml or ElementTree 1.3+ 

Salida:

blah blah link END 
1

que acabo de escribir esto. Lo necesito. Utiliza html2text y toma una ruta de archivo, aunque yo preferiría una URL. El resultado de html2text se almacena en TextFromHtml2Text.text imprimirlo, almacenarlo, alimentarlo a su mascota canario.

import html2text 
class TextFromHtml2Text: 

    def __init__(self, url = ''): 
     if url == '': 
      raise TypeError("Needs a URL") 
     self.text = "" 
     self.url = url 
     self.html = "" 
     self.gethtmlfile() 
     self.maytheswartzbewithyou() 

    def gethtmlfile(self): 
     file = open(self.url) 
     for line in file.readlines(): 
      self.html += line 

    def maytheswartzbewithyou(self): 
     self.text = html2text.html2text(self.html) 
+0

También podría escribir esto como 'import urllib, html2text [break] def get get_text_from_html_url (url): [break] return html2text.html2text (urllib.urlopen (url) .read())' más corto y más limpio –

1

Hay una manera simple de esto:

def remove_html_markup(s): 
    tag = False 
    quote = False 
    out = "" 

    for c in s: 
      if c == '<' and not quote: 
       tag = True 
      elif c == '>' and not quote: 
       tag = False 
      elif (c == '"' or c == "'") and tag: 
       quote = not quote 
      elif not tag: 
       out = out + c 

    return out 

se explica La idea aquí: http://youtu.be/2tu9LTDujbw

Puede ver su funcionamiento aquí: http://youtu.be/HPkNPcYed9M?t=35s

PS - Si estás interesado en la clase (sobre la depuración inteligente con python) le doy un enlace: http://www.udacity.com/overview/Course/cs259/CourseRev/1. ¡Es gratis!

De nada! :)