將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'))