如何在BeautifulSoup.contents中保留空格

时间:2015-11-18 18:52:45

标签: python beautifulsoup

我在网上找到的大多数例子都显示了如何删除空格 - 但在我的情况下我需要保留它...我有

html = "I can flip this whole thing with one hand\n               <span>D#m</span>\nThe ringleader man\n<span>A#</span>                           <span>Dm</span>                          <span>A#</span>\nI know~~~~ it's a fact that you'd rather just have some of me instead"
bs = BeautifulSoup(html, 'html.parser')
content = (unicode('').join(unicode(content) for content in bs.contents))

我希望保留空格(“html”变量包含预标记的内容) - 但它似乎用一个空格替换多个空格。

如何保留/获取给定beautifulsoup解析器的原始内容?

1 个答案:

答案 0 :(得分:2)

如果要解析的内容位于&lt; pre&gt;中,则html解析器似乎只保留空格。标签 - 在我的情况下,pre标签被删除。添加

html = "<pre>" + html + "</pre>"

保留了空白。

相关问题