将NCR字符转换成真实字符
以 &# 或 &#x 开头的字符串叫做 NCR 字符,在浏览器中查看会直接转换成中文。
在爬虫中使用 lxml 解析得到网页内容的html代码时,网页中的中文都会显示成 NCR 字符的形式。
通过 xpath 或 pyquery 获得的网页的html字符串中的中文会变成形如“不同的出行方式” 的格式,可通过 py2.x下的HTMLParser 或 py3.x下的html 的 unescape() 方法来转换成能看懂的中文字符。
解决方法:
# Python 2.6-3.3
# You can use the HTML parser from the standard lib
# Python 2.6-2.7
import HTMLParserh = HTMLParser.HTMLParser()# Python 3.0-3.5import html.parserh = html.parser.HTMLParser()
# Python 2.6-3.5 (with six)
from six.moves import html_parserh = html_parser.HTMLParser()
print(h.unescape("<p>不同的出行方式,体验是不一样的。</p>"))
#<p>不同的出行方式,体验是不一样的。</p>
# Python 3.4+ HTMLParser.unescape is deprecated, and was supposed to be removed in 3.5, although it was left in by mistake.
It will be removed from the language soon.
Instead, use html.unescape():
import html
print(html.unescape('£682m'))
2016.11.26
发现简书莫名把我用&#举的例子还原成了中文……只好把例子删了,至于代码部分大家意会即可,我就不改了
网友评论