python - 如何在 BeautifulSoup.contents 中保留空格

标签 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”变量包含 pre 标记的内容)——但它似乎用一个空格替换了多个空格。

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

最佳答案

如果您正在解析的内容位于

 标记中,html 解析器似乎只保留空格——在我的例子中,pre 标记已被删除。添加

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

保留空白。

关于python - 如何在 BeautifulSoup.contents 中保留空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33788047/

相关文章:

python - pydrive.auth.RefreshError : Access token refresh failed: invalid_grant: Token has been expired or revoked

python - 即使在其中的命令退出后继续 for 循环

python - pandas 中的项目总和并写入文件

python - 将 HTML 行解析为 CSV

python - BeautifulSoup 或请求不阅读网页的某些部分

Python-每天从没有任何提要的网站上抓取新闻文章

python - BeautifulSoup Instagram 帖子 html 抓取

python - 如果将 input() 转换为字符串,是否可以安全使用?

python - 使用 python 登录网站并进行网页抓取

python - 使用 -m 运行 python 脚本时,为什么不调用 __init__.py?