2013-09-06 1 views
12

lxml要素からテキストコンテンツを抽出するときに、<br>タグを\nとして保存します。<br>は、lxml.htmlのtext_content()またはそれと同等の改行としてどのように保存できますか?

例コード:

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' 
+0

解析後はどうなっていますか? –

答えて

17

は、あなたが期待している結果を与える必要があり、各<br />要素の末尾に\n文字を付加:

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

ありがとう、私はちょうどこれについて自分自身を見つけた、私が投稿した例のhtmlでテストを実行しようとしています。 – extempo

+0

更新されたサンプルHTMLを使用してコード例を更新しました。 –

関連する問題