python

超轻量级php框架startmvc

python处理html转义字符的方法详解

更新时间:2020-04-22 08:05:01 作者:startmvc
本文实例讲述了python处理html转义字符的方法。分享给大家供大家参考,具体如下:最近在

本文实例讲述了python处理html转义字符的方法。分享给大家供大家参考,具体如下:

最近在用Python处理网页数据时,经常遇到一些html转义字符(也叫html字符实体),例如<> 等。字符实体一般是为了表示网页中的预留字符,比如>用>表示,防止被浏览器认为是标签,具体参考w3school的HTML 字符实体。虽然很有用,但是它们会极度影响对于网页数据的解析。为了处理这些转义字符,有如下解决方案:

1、使用HTMLParser处理


import HTMLParser
html_cont = " asdfg>123<"
html_parser = HTMLParser.HTMLParser()
new_cont = html_parser.unescape(html_cont)
print new_cont #new_cont = " asdfg>123<"

转换回去(只是空格转不回去了):


import cgi
new_cont = cgi.escape(new_cont)
print new_cont #new_cont = " asdfg>123<"

2、直接挨个替换


html_cont = " asdfg>123<"
new_cont = new_cont.replace(' ', ' ')
print new_cont #new_cont = " asdfg>123<"
new_cont = new_cont.replace('>', '>')
print new_cont #new_cont = " asdfg>123<"
new_cont = new_cont.replace('<', '<')
print new_cont #new_cont = " asdfg>123<"

不知道还有没有更好的办法。

另外stackoverflow上给出了在xml中处理转义字符的解答:python - What's the best way to handle  -like entities in XML documents with lxml? - Stack Overflow。

python html 转义字符