2013-09-06 4 views
12

Voglio conservare <br> tag come \n quando si estrae il contenuto del testo da elementi lxml.Come posso conservare <br> come nuove righe con lxml.html TEXT_CONTENT() o equivalente?

codice Esempio:

fragment = '<div>This is a text node.<br/>This is another text node.<br/><br/><span>And a child element.</span><span>Another child,<br> with two text nodes</span></div>'

h = lxml.html.fromstring(fragment) 

uscita:

> h.text_content() 
'This is a text node.This is another text node.And a child element.Another child, with two text nodes' 
+0

Che aspetto ha dopo l'analisi? –

risposta

17

Anteporre un carattere \n alla coda di ogni elemento <br /> dovrebbe dare il risultato che vi aspettate:

>>> import lxml.html as html 
>>> fragment = '<div>This is a text node.<br/>This is another text node.<br/><br/><span>And a child element.</span><span>Another child,<br> with two text nodes</span></div>' 
>>> doc = html.document_fromstring(fragment) 
>>> for br in doc.xpath("*//br"): 
     br.tail = "\n" + br.tail if br.tail else "\n" 

>>> doc.text_content() 
'This is a text node.\nThis is another text node.\n\nAnd a child element.Another child,\n with two text nodes' 
>>> fragment 
'<div>This is a text node.<br/>This is another text node.<br/><br/><span>And a child element.</span><span>Another child,<br> with two text nodes</span></div>' 
+0

Grazie, l'ho appena scoperto, provando a eseguire un test con l'html di esempio che ho pubblicato. – extempo

+0

Ho aggiornato il mio esempio di codice utilizzando l'html di esempio aggiornato. –

Problemi correlati