Skip to main content
 首页 » 编程设计

python之奇怪的 lxml 行为

2025年05月04日9unruledboy

考虑以下片段:

import lxml.html 
 
html = '<div><br />Hello text</div>' 
doc = lxml.html.fromstring(html) 
text = doc.xpath('//text()')[0] 
print lxml.html.tostring(text.getparent()) 
#prints <br>Hello text 

我期待看到 '<div><br />Hello text</div>' ,因为 br不能有嵌套文本并且是“自封闭的”(我的意思是 /> )。如何制作lxml处理对了吗?

请您参考如下方法:

HTML 没有自闭合标签。这是一个 xml 的东西。

import lxml.etree 
 
html = '<div><br />Hello text</div>' 
doc = lxml.etree.fromstring(html) 
text = doc.xpath('//text()')[0] 
print lxml.etree.tostring(text.getparent()) 

打印

<br/>Hello text 

请注意,文本不在标签内。 lxml 有一个“tail”的概念。

>>> print text.text 
None 
>>> print text.tail 
Hello text