手机
当前位置:查字典教程网 >脚本专栏 >python >python处理html转义字符的方法详解
python处理html转义字符的方法详解
摘要:本文实例讲述了python处理html转义字符的方法。分享给大家供大家参考,具体如下:最近在用Python处理网页数据时,经常遇到一些htm...

本文实例讲述了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程序设计有所帮助。

【python处理html转义字符的方法详解】相关文章:

Python生成随机数的方法

python和shell变量互相传递的几种方法

Python中的魔法方法深入理解

python逐行读取文件内容的三种方法

Python中文件遍历的两种方法

Python列表推导式的使用方法

使用Python进行稳定可靠的文件操作详解

Python httplib,smtplib使用方法

python3访问sina首页中文的处理方法

python正则表达式re模块详解

精品推荐
分类导航