2015-10-15 65 views
6

This question è stato chiesto quattro anni fa, ma la risposta non è più aggiornata per BS4.Come trovare tutti i commenti con Beautiful Soup

Voglio eliminare tutti i commenti nel mio file html usando una bella zuppa. Dal momento che BS4 rende ogni comment as a special type of navigable string, ho pensato che questo codice dovrebbe funzionare:

for comments in soup.find_all('comment'): 
    comments.decompose() 

In modo che non ha funzionato .... Come faccio a trovare tutti i commenti utilizzando BS4?

+0

Questa [risposta] (http://stackoverflow.com/a/3507360/771848) dovrebbe ancora funzionare, suppongo. – alecxe

+0

Ricevo che il "nome globale" commento "non è definito" – Joseph

+1

Mi rendo conto che questo è vecchio, ma @Joseph, se si importa commento da bs4 dovrebbe funzionare – atarw

risposta

8

È possibile passare una funzione per find_all() per aiutarlo a verificare se la stringa è un commento.

Per esempio io ho seguito html:

<body> 
    <!-- Branding and main navigation --> 
    <div class="Branding">The Science &amp; Safety Behind Your Favorite Products</div> 
    <div class="l-branding"> 
     <p>Just a brand</p> 
    </div> 
     <!-- test comment here --> 
     <div class="block_content"> 
      <a href="https://www.google.com">Google</a> 
    </div> 
</body> 

Codice:

from bs4 import BeautifulSoup as BS 
from bs4 import Comment 
.... 
soup=BS(html,'html.parser') 
comments=soup.find_all(string=lambda text:isinstance(text,Comment)) 
for c in comments: 
    print c 
    print "===========" 
    c.decompose() 

l'output sarà:

Branding and main navigation 
============ 
test comment here 
============ 

BTW, penso che il motivo per cui non lo fa find_all('Comment') il lavoro è (dal documento BeautifulSoup):

Inserisci un valore per nome e dirai a Beautiful Soup di considerare solo i tag con determinati nomi. Le stringhe di testo verranno ignorate, così come i tag i cui nomi non corrispondono.

+0

Sono contento di aver trovato la tua risposta, grazie! Qualche idea su come potremmo scrivere senza usare lambda? – JinSnow

6

Due cose che dovevo fare:

In primo luogo, durante l'importazione Beautiful Soup

In secondo luogo, ecco il codice per estrarre i commenti

for comments in soup.findAll(text=lambda text:isinstance(text, Comment)): 
    comments.extract()