Как я могу сохранить ‹br› как новые строки с помощью lxml.html text_content() или эквивалентного?

Я хочу сохранить теги <br> как \n при извлечении текстового содержимого из элементов lxml.

Пример кода:

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)

Выход:

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

person extempo    schedule 06.09.2013    source источник
comment
Как это выглядит после разбора?   -  person Ofir Israel    schedule 06.09.2013


Ответы (1)


Добавление символа \n в конец каждого элемента <br /> должно дать ожидаемый результат:

>>> 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>'
person bob esponja    schedule 06.09.2013
comment
Спасибо, я только что узнал об этом сам, пытаясь запустить тест с примером html, который я разместил. - person extempo; 06.09.2013