首页  >  文章  >  后端开发  >  python处理html转义字符

python处理html转义字符

高洛峰
高洛峰原创
2017-03-01 13:27:571961浏览

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

最近在用Python处理网页数据时,经常遇到一些html转义字符(也叫html字符实体),例如a8093152e673feb7aba1828c43532094 等。字符实体一般是为了表示网页中的预留字符,比如>用>表示,防止被浏览器认为是标签,具体参考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(&#39; &#39;, &#39; &#39;)
print new_cont #new_cont = " asdfg>123<"
new_cont = new_cont.replace(&#39;>&#39;, &#39;>&#39;)
print new_cont #new_cont = " asdfg>123<"
new_cont = new_cont.replace(&#39;<&#39;, &#39;<&#39;)
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转义字符相关文章请关注PHP中文网!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn