將NCR字符轉(zhuǎn)換成真實(shí)字符
以 &# 或 &#x 開頭的字符串叫做 NCR 字符,在瀏覽器中查看會直接轉(zhuǎn)換成中文。
在爬蟲中使用 lxml 解析得到網(wǎng)頁內(nèi)容的html代碼時(shí),網(wǎng)頁中的中文都會顯示成 NCR 字符的形式。
通過 xpath 或 pyquery 獲得的網(wǎng)頁的html字符串中的中文會變成形如“不同的出行方式” 的格式,可通過 py2.x下的HTMLParser 或 py3.x下的html 的 unescape() 方法來轉(zhuǎn)換成能看懂的中文字符。
解決方法:
# 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>不同的出行方式,體驗(yàn)是不一樣的。</p>"))
#<p>不同的出行方式,體驗(yàn)是不一樣的。</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
發(fā)現(xiàn)簡書莫名把我用&#舉的例子還原成了中文……只好把例子刪了,至于代碼部分大家意會即可,我就不改了