python转义html字符串,用python处理html代码的转义与复原

抓网页数据经常遇到例如>或者 这种HTML转义符,抓到字符串里很是烦人。

比方说一个从网页中抓到的字符串

html = '<abc>'

用Python可以这样处理:

importHTMLParser

html_parser =HTMLParser.HTMLParser()

txt = html_parser.unescape(html) #这样就得到了txt = ''

如果还想转回去,可以这样:

importcgi

html = cgi.escape(txt) #这样又回到了 html = '<abc&gt'

来回转的功能还分了两个模块实现,挺奇怪。没找到更优美的方法,欢迎补充哈~

--------------------------------------------------

html的escape和unescape

http://stackoverflow.com/questions/275174/how-do-i-perform-html-decoding-encoding-using-python-django

For html encoding, there's cgi.escape from the standard library:

>> help(cgi.escape)

cgi.escape = escape(s, quote=None)

Replace special characters "&", "" to HTML-safe sequences.

If the optional flag quote is true, the quotation mark character (")

is also translated.

For html decoding, I use the following:

from htmlentitydefs import name2codepoint

# for some reason, python 2.5.2 doesn't have this one (apostrophe)

name2codepoint['#39'] = 39

def unescape(s):

"unescape HTML code refs; c.f. http://wiki.python.org/moin/EscapingHtml"

return re.sub('&(%s);' % '|'.join(name2codepoint),

lambda m: unichr(name2codepoint[m.group(1)]), s)

For anything more complicated, I use BeautifulSoup.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值