gpt4 book ai didi

Python - Beautiful Soup - 如何用不间断空格替换字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 10:31:18 24 4
gpt4 key购买 nike

我有以下 HTML 片段:

<div><span>This is some text.</span></div>

我想用单个不间断空格(即  )替换 div 标签中的 span,结果是以下 HTML :

<div>&nbsp;</div>

我试过了

soup.div.span.replace_with('&nbsp;')

但结果是

<div>&amp;nbsp;</div>

我也试过

soup.div.span.replace_with(' ') // single space character

但结果是

<div> </div>

如何插入不间断空格实体?

最佳答案

 实体代表U+00A0 NO-BREAK SPACE字符,使用它作为 BeautifulSoup 将所有文本内容视为 Unicode:

soup.div.span.replace_with(u'\xa0')

演示:

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''<div><span>This is some text.</span></div>''')
>>> soup.div.span.replace_with(u'\xa0')
<span>This is some text.</span>
>>> soup.encode_contents(formatter='html')
'<html><body><div>&nbsp;</div></body></html>'

请注意,我需要使用 output formatter强制 BeautifulSoup 在输出中使用实体;默认是使用文字字符(这对浏览器来说很好)。

关于Python - Beautiful Soup - 如何用不间断空格替换字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26334461/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com