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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

holybin   2021-03-22 我要评论
想了解python处理html转义字符的方法详解的相关内容吗,holybin在本文为您仔细讲解python处理html转义字符的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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程序设计有所帮助。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们