python html 特殊字符转义,在Python中转义特殊的HTML字符

The cgi module that comes with Python has an escape() function:import cgi

s = cgi.escape( """& < >""" ) # s = "& < >"

However, it doesn't escape characters beyond &, . If it is used as cgi.escape(string_to_escape, quote=True), it also escapes ".

Here's a small snippet that will let you escape quotes and apostrophes as well:html_escape_table = {

"&": "&",

'"': """,

"'": "'",

">": ">",

"

}

def html_escape(text):

"""Produce entities within text."""

return "".join(html_escape_table.get(c,c) for c in text)

You can also use escape() from xml.sax.saxutils to escape html. This function should execute faster. The unescape() function of the same module can be passed the same arguments to decode a string.from xml.sax.saxutils import escape, unescape

# escape() and unescape() takes care of &, < and >.

html_escape_table = {

'"': """,

"'": "'"

}

html_unescape_table = {v:k for k, v in html_escape_table.items()}

def html_escape(text):

return escape(text, html_escape_table)

def html_unescape(text):

return unescape(text, html_unescape_table)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值