如何从美丽的汤中删除XML编码



我想知道如何删除在BeautifulSoup中通过Prettify创建的编码。示例:

tree='''<A attribute1="1" attribute2="2">
 <B>
  <C/>
 </B>
</A>'''
from collections import defaultdict
from bs4 import BeautifulSoup as Soup
root = Soup(tree, 'lxml-xml')
print root.prettify().replace('n', '')

输出看起来像

<?xml version="1.0" encoding="utf-8"?><A attribute1="1" attribute2="2"> <B>  <C/> </B></A>

我想要:

<A attribute1="1" attribute2="2"> <B>  <C/> </B></A>

有几种方法可以解决:

第一个,请致电root.decode_contents(),它将为您提供非预言内容的输出。

或分别将每个块的每个块都在加入。像这样:'n'.join(x.prettify() for x in root.contents)

最新更新