【问题标题】:How to remove <?xml version="1.0" encoding="utf-8"?> when using "xml" in Beautiful Soup在 Beautiful Soup 中使用“xml”时如何删除 <?xml version="1.0" encoding="utf-8"?>
【发布时间】:2013-10-13 14:39:07
【问题描述】:
from bs4 import BeautifulSoup

xmlcontent = "some text with <tags>"

bs = BeautifulSoup(xmlcontent, "xml")

print bs

输出:

<?xml version="1.0" encoding="utf-8"?>
some text with <tags>

是否可以不输出:

<?xml version="1.0" encoding="utf-8"?>

我知道如果使用lxml,我可以删除添加的&lt;body&gt;标签:

bs = BeautifulSoup(xmlcontent, "lxml")

print bs.body.next

是否有与xml 一起使用的等效项,以便不包括xml 版本和编码?

我选择使用xml 而不是lxml,因为要解析的内容通常都是xml 格式——这是最好的选择,还是我可以只使用lxml 来处理xml 内容?

【问题讨论】:

    标签: python-2.7 xml-parsing beautifulsoup


    【解决方案1】:

    这似乎有效:

    from bs4 import BeautifulSoup
    
    xmlcontent = "some text with <tags>"
    
    bs = BeautifulSoup(xmlcontent, "xml")
    
    bs = bs.encode_contents()
    
    print type(bs) # it's a string
    
    print bs
    
    # some text with <tags>
    

    【讨论】:

      猜你喜欢
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多