如何在BeautifulSoup.contents中保留空格 [英] How do I keep whitespace in BeautifulSoup.contents

查看:205
本文介绍了如何在BeautifulSoup.contents中保留空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上找到的大多数示例都显示了如何删除空格-但就我而言,我需要保留它..我有

Most examples I find online show how to remove whitespace - but in my case I need to keep it.. I have

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"变量包含pre标记的内容),但是似乎用一个空格代替了多个空格.

Which I expect to keep the whitespace (the "html" variable contains the contents of a pre tag) -- but it seems to replace multiple spaces with a single space.

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

How do I keep/get the raw contents of a given beautifulsoup parser?

推荐答案

如果要解析的内容在< pre>标记中,则html解析器似乎仅保留空白-在我的情况下,pre标记已删除.添加

The html parser seems to only keeps whitespace if the content you are parsing is in a <pre> tag -- in my case, the pre tag was removed. Adding

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

保留空白.

这篇关于如何在BeautifulSoup.contents中保留空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆