如何在 Beautifulsoup 标签中插入一个空格(&nbsp)? [英] How to insert a blank space(&nbsp) into a Beautifulsoup tag?

查看:42
本文介绍了如何在 Beautifulsoup 标签中插入一个空格(&nbsp)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将&nbsp"添加到 Beautifulsoup 标签中.BS 将 tag.string 转换为 \  而不是 &nbsp.这一定是一些编码问题,但我无法弄清楚.

I'm trying to add a '&nbsp' into a Beautifulsoup tag. BS converts the tag.string to \&ampamp;nbsp; instead of &nbsp. It has to be some encoding issue but I can't figure it out.

请注意:忽略后面的\"字符.我必须添加它,这样 stackoverflow 才能正确格式化我的问题.

PLEASE NOTE: ignore the back '\' character. I had to add it so stackoverflow would format my question correctly.

import bs4 as Beautifulsoup

html = "<td><span></span></td>"
soup = Beautifulsoup(html)
tag = soup.find("td")
tag.string = "&nbsp;"

当前输出为 html = "\&nbsp;"

Current output is html = "\&amp;nbsp;"

有什么想法吗?

推荐答案

默认情况下 BeautifulSoup 使用 minimal 输出格式化程序并转换 HTML 实体.

By default BeautifulSoup uses minimal output formatter and converts HTML entities.

解决办法是将输出格式设置为None,引用来自BS源(PageElement docstring):

The solution is to set output formatter to None, quote from BS source (PageElement docstring):

# There are five possible values for the "formatter" argument passed in
# to methods like encode() and prettify():
#
# "html" - All Unicode characters with corresponding HTML entities
#   are converted to those entities on output.
# "minimal" - Bare ampersands and angle brackets are converted to
#   XML entities: &amp; &lt; &gt;
# None - The null formatter. Unicode characters are never
#   converted to entities.  This is not recommended, but it's
#   faster than "minimal".

示例:

from bs4 import BeautifulSoup


html = "<td><span></span></td>"
soup = BeautifulSoup(html, 'html.parser')
tag = soup.find("span")
tag.string = '&nbsp;'

print soup.prettify(formatter=None)

印刷品:

<td>
 <span>
  &nbsp;
 </span>
</td>

希望有所帮助.

这篇关于如何在 Beautifulsoup 标签中插入一个空格(&amp;nbsp)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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