fromstring() -> tostring() 修改了整体 HTML 结构
我正在尝试使用lxml.html来写一个清理程序,目的是去掉那些没有内容的空DIV元素。在调试的时候,我发现用标准的tostring()和fromstring()进行循环处理时,会改变我的HTML。首先,它会去掉外面的body标签,其次,它还会改变DIV的结构。
这是为什么呢?
(Pdb) from lxml.html import fromstring, tostring
(Pdb) print html
<body>
<div></div>
<p>hello world</p>
<div> </div>
<p><div> </div></p>
</body>
(Pdb) print tostring(fromstring(html))
<div>
<div></div>
<p>hello world</p>
<div> </div>
<p></p><div> </div>
</div>
1 个回答
3
没错。虽然你的例子结构上是正确的,但它不是有效的HTML,所以lxml会尽量修正它。特别是,div元素不能放在p元素里面,而且根标签不能是body。你可以使用etree模块来处理:
from lxml.etree import fromstring, tostring