python3解决爬取网页中文显示为16进制数的问题

最近发现一个问题,网页爬取出来的中文显示为十六进制。代码如下:

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";

猜你喜欢

转载自blog.csdn.net/eagle1024/article/details/81036021