2009-02-28 18 views
6

Come posso rimuovere tutto l'HTML da una stringa in Python? Per esempio, come posso rivolgermi:Rimozione HTML Python

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

in

blah blah link 

Grazie!

+0

Potrebbe essere eccessivo per i vostri scopi, ma date una prova a BeautifulSoup se le vostre stringhe hanno HTML più complicato o malformato. Avvertenza: non penso che sia disponibile per Python 3.0 ancora. – bernie

risposta

7

È possibile utilizzare un'espressione regolare per rimuovere tutti i tag:

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

È possibile semplificare l'espressione regolare a '<.*?>' che otterrà gli stessi risultati, ma questo presuppone l'HTML correttamente formattato, così come il tuo. – UnkwnTech

+0

Devi controllare se citato>, o quelli non sono ammessi? Puoi avere o qualcosa del genere? –

+0

@Unkwntech: Io preferisco <[^>] *> oltre <.*?> poiché il primo non ha bisogno di mantenere il backtracking per trovare la fine del tag. –

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

Quando la soluzione espressione regolare colpisce un muro, provare questo super facile (e affidabile) Programma 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 colpisce anche lo stesso muro. Vedi http://stackoverflow.com/questions/598817/python-html-removal/600471#600471 – jfs

10

C'è anche una piccola libreria chiamata stripogram che può essere utilizzato a spogliare alcuni o tutti i tag HTML.

Si può usare in questo modo:

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) 

Quindi, se si vuole mettere a nudo semplicemente fuori tutto il codice HTML, si passa valid_tags =() per la prima funzione.

È possibile trovare il documentation here.

2

html2text farà qualcosa del genere.

+0

html2text è ottimo per produrre output ben formattati e leggibili senza un passaggio aggiuntivo. Se tutte le stringhe HTML che devi convertire sono semplici come il tuo esempio, allora BeautifulSoup è la strada da percorrere. Se più complesso, html2text fa un ottimo lavoro nel preservare l'intento leggibile dell'originale. –

5

regexs, BeautifulSoup, html2text non funzionano se un attributo ha '>' in esso. Vedere Is “>” (U+003E GREATER-THAN SIGN) allowed inside an html-element attribute value?

'soluzione basata-parser' HTML/XML potrebbe aiutare in questi casi per esempio, stripogramsuggested by @MrTopf funziona.

Ecco ElementTree soluzione basata su:

####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+ 

uscita:

blah blah link END 
1

ho appena scritto questo. Ne ho bisogno. Usa html2text e prende un percorso di file, anche se preferirei un URL. L'output di html2text è memorizzato in TextFromHtml2Text.text stampalo, salvalo, alimentalo al tuo canarino domestico.

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

Si potrebbe anche scrivere come "import urllib, html2text [break] def get_text_from_html_url (url): [break] return html2text.html2text (urllib.urlopen (url) .read())' più corto e più pulito –

1

C'è un modo semplice per questo:

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 

L'idea è qui spiegato: http://youtu.be/2tu9LTDujbw

Potete vederlo lavorare qui: http://youtu.be/HPkNPcYed9M?t=35s

PS - Se siete interessato alla classe (sul debugging intelligente con python) ti do un link: http://www.udacity.com/overview/Course/cs259/CourseRev/1. È gratis!

Prego! :)