我有大量必须转换为XML的HTML文档。并非所有看起来都完全一样。例如,下面的示例以HTML注释标记结尾,而不是HTML标记。
请注意,此问题与this one相关。
这是我的代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<comment>this is an HTML comment</comment>
<comment>this is another HTML comment</comment>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
...
<comment>here is a comment inside the head tag</comment>
</head>
<body>
...
<comment>Comment inside body tag</comment>
<comment>Another comment inside body tag</comment>
<comment>There could be many comments in each file and scattered, not just 1 in the head and three in the body. This is just a sample.</comment>
</body>
</html>
<comment>This comment is the last line of the file</comment>
我希望使用名为<root>
的自定义标记包装整个文档。到目前为止,我能做的最好的事情就是<root>
周围<html>
。
root_tag = bs4.Tag(name="root")
soup.html.wrap(root_tag)
如何定位<root>
元素以使其包装整个文档?
答案 0 :(得分:0)
有点粗糙,因为这只是包裹<root> </root>
看看它是否适用于您的用例:
def root_wrap(file):
fin = open(file, 'r+')
fin.write('<root>')
for line in fin:
fin.write(line)
fin.write('</root>')
fin.close()