2013-09-06 11 views
12

Chcę zachować znaczniki <br> jako \n podczas wyodrębniania treści tekstowej z elementów lxml.Jak mogę zachować <br> jako znaki nowej linii za pomocą lxml.html text_content() lub odpowiednika?

Przykładowy kod:

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) 

wyjściowa:

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

Jak to wygląda po parsowaniu? –

Odpowiedz

17

Poprzedzenie się \n znak na ogonie każdego elementu <br /> powinny dać wynik czekasz:

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

Dzięki, sam się o tym dowiedziałem, próbując uruchomić test z zamieszczonym przeze mnie przykładem html. – extempo

+0

Zaktualizowałem przykład mojego kodu przy użyciu zaktualizowanego przykładu html. –

Powiązane problemy