# -*- coding: utf-8 -*-
text = '<abc>'
text2 = '<abc>'
from bs4 import BeautifulSoup
print('----------------------bs4转义为正常字符----------------------------------')
soup = BeautifulSoup(text, features="html.parser")
print(soup.text)# <abc>
from lxml import etree
print('----------------------lxml转义为正常字符----------------------------------')
html=etree.HTML(text)
# 使用xpath获取content中的所有字符串
print(html.xpath("string(.)"))# <abc>
from html.parser import HTMLParser
print('----------------------html.parser转义为正常字符----------------------------------')
html_parser = HTMLParser()
text3 = html_parser.unescape(text)
print(text3)# <abc>
import html
print('----------------------html方法转义为正常字符----------------------------------')
text3=html.unescape(text)
print(text3) # <abc>
print('----------------------html方法转义为html字符----------------------------------')
text4=html.escape(text2)
print(text4) # <abc>
from xml.sax.saxutils import unescape,escape
print('----------------------xml.sax.saxutils转义为正常字符------------------------')
text3=unescape(text)
print(text3)# <abc>
print('----------------------xml.sax.saxutils转义为html字符------------------------')
text4=escape(text2)
print(text4) # <abc>
import cgi
print('----------------------cgi转义为html字符----------------------------------')
text3 = cgi.escape(text2)
print(text3)# <abc>
参考:https://www.cnblogs.com/xuxn/archive/2011/08/12/parse-html-escape-characters-in-python.html
https://blog.csdn.net/zhusongziye/article/details/78786519
https://www.cnblogs.com/du-jun/p/10345067.html
抓网页数据经常遇到例如>或者 这种HTML转义符什么是转义字符在 HTML 中 <、>、& 等字符有特殊含义(<,> 用于标签中,& 用于转义),他们不能在 HTML 代码中直接使用,如果要在网页中显示这些符号,就需要使用 HTML 的转义字符串(Escape Sequence),例如 < 的转义字符是 &lt;,浏览器渲染 HTML 页面时,会自动把转移字符串换成真实字符。转义字符
您可以使用 Python 的 open 函数读取本地 HTML 文件,并使用 read 方法将其读取为字符串。接下来,您可以使用 replace 方法将其中的换行字符替换为空格,最后将其转换为一行字符串。
以下是一个示例代码:
with open("file.html", "r") as f:
html_content = f.read()
one_line_string = ht...
本文实例讲述了python对html代码进行escape编码的方法。分享给大家供大家参考。具体分析如下:
python包含一个cgi模块,该模块有一个escape函数可以用来对html代码进行编码转换
import cgi
s1 = "Hello <strong>world</strong>"
s2 = cgi.escape(s1)
assert s2 == "Hello <strong>world</strong>"
希望本文所述对大家的Python程序设计有所帮助。
您可能感兴趣的文章:python实现unicode转中文及转换默认编码的方
本文实例讲述了python处理html转义字符的方法。分享给大家供大家参考,具体如下:
最近在用Python处理网页数据时,经常遇到一些html转义字符(也叫html字符实体),例如<> 等。字符实体一般是为了表示网页中的预留字符,比如>用>表示,防止被浏览器认为是标签,具体参考w3school的HTML 字符实体。虽然很有用,但是它们会极度影响对于网页数据的解析。为了处理这些转义字符,有如下解决方案:
1、使用HTMLParser处理
import HTMLParser
html_cont = " asdfg>123<"
html_parser = HTMLParser.HTMLParse
| 转义字符 | 描述 |
| \ | (在行尾时)续行符 |
| \\ | 反斜杠符号 |
| `\'` | 单引号