抓网页数据经常遇到例如 > 或者 这种HTML转义符
>
在 HTML 中 < 、 > 、 & 等字符有特殊含义(<,> 用于标签中,& 用于转义),他们不能在 HTML 代码中直接使用,如果要在网页中显示这些符号,就需要使用 HTML 的转义字符串(Escape Sequence),例如 < 的转义字符是 < ,浏览器渲染 HTML 页面时,会自动把转移字符串换成真实字符。
<
>
&
<
转义字符(Escape Sequence)由三部分组成:第一部分是一个 & 符号,第二部分是实体(Entity)名字,第三部分是一个分号。 比如,要显示小于号(<),就可以写 < 。
用 Python 来处理转义字符串有多种方式,而且 py2 和 py3 中处理方式不一样,在 python2 中,反转义串的模块是 HTMLParser 。
HTMLParser
# python2 import HTMLParser >>> HTMLParser().unescape('a=1&b=2') 'a=1&b=2'
Python3 把 HTMLParser 模块迁移到 html.parser
html.parser
# python3 >>> from html.parser import HTMLParser >>> HTMLParser().unescape('a=1&b=2') 'a=1&b=2'
到 python3.4 之后的版本,在 html 模块新增了 unescape 和 escape 方法。
unescape
escape
# python3.4 >>> import html >>> html.unescape('a=1&b=2') 'a=1&b=2' >>> html.escape('a=1&b=2') 'a=1&b=2'
推荐最后一种写法,因为 HTMLParser.unescape 方法在 Python3.4 就已经被废弃掉不推荐使用,意味着之后的版本有可能会被彻底移除。
另外,sax 模块也有支持反转义的函数
>>> from xml.sax.saxutils import unescape,escape >>> unescape('a=1&b=2') 'a=1&b=2' >>> escape('a=1&b=2') 'a=1&b=2'
# -*- 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