最近發現一個問題,網頁爬取出來的中文顯示爲十六進制。代碼如下:
import urllib.request as rst
import re
import requests
response = rst.urlopen('http://hq.sinajs.cn/list=s_sz000001')
print("dest text=", stockStr)
結果如下:
dest text= b'var hq_str_s_sz000001="\xc6\xbd\xb0\xb2\xd2\xf8\xd0\xd0,8.88,0.00,0.00,603378,53540";\n'
我試着改爲utf8的編碼,結果報錯了。
print("dest text=", stockStr.decode('utf-8'))
提示解碼失敗:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 25: invalid start byte
後來我想,這個網頁可能不是utf8編碼的。於是查看了網頁的編碼。
import urllib.request as rst
import re
import requests
res=requests.get('http://hq.sinajs.cn/list=s_sz000001')
print(res.encoding)
發現編碼是gbk。
於是解碼爲gbk就搞定了。
print("dest text=", stockStr.decode('gbk'))
顯示結果如下:
dest text= var hq_str_s_sz000001="平安銀行,8.88,0.00,0.00,603378,53540";