2013-09-06 14 views
12

Tôi muốn giữ lại các thẻ <br> làm \n khi trích xuất nội dung văn bản từ các phần tử lxml.Tôi làm cách nào để bảo vệ <br> làm dòng mới với lxml.html text_content() hoặc tương đương?

Ví dụ mã:

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) 

Output:

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

Trông giống như thế nào sau khi phân tích cú pháp? –

Trả lời

17

prepending một nhân vật \n đến đuôi của mỗi phần tử <br /> nên cung cấp cho các kết quả mà bạn đang mong đợi:

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

Cảm ơn, tôi vừa phát hiện ra điều này, cố chạy thử nghiệm với ví dụ html tôi đã đăng. – extempo

+0

Tôi đã cập nhật ví dụ về mã của mình bằng cách sử dụng html mẫu được cập nhật của bạn. –

Các vấn đề liên quan