手机
当前位置:查字典教程网 >脚本专栏 >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局部赋值的规则

wxpython中利用线程防止假死的实现方法

python读取注册表中值的方法

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

python去掉字符串中重复字符的方法

python实现问号表达式(?)的方法

python中文乱码的解决方法

Python标准库与第三方库详解

netbeans7安装python插件的方法图解

vc6编写python扩展的方法分享

精品推荐
分类导航