×

python 乱码 转码 utf8 decode

抓取网页源代码遇到的乱码转码方案

鹭岛小千 鹭岛小千 发表于2021-09-02 22:42:38 浏览648 评论0

抢沙发发表评论

【问题描述】使用requests库抓取网页源代码输出到VSCode终端出现以下两种乱码,如何才能正确显示呢?

37-1.png

37-2.png

【小千解答】进行相应的数据类型转换或转码,示例代码如下:

import requests

url = 'http://fund.eastmoney.com/company/default.html'
res = requests.request('GET',url)
if (res.status_code == 200):
    # 处理前
    print(res.content[:300])
    # 方法1
    print(bytes.decode(res.content)[:300])
    # 方法2
    print(str(res.content,'utf-8')[:300])
    # 方法3
    print(res.content.decode('utf-8')[:300])
    
    # 转码前
    print(res.text[:300])
    # 转码后
    print(res.text.encode(res.encoding).decode('utf-8')[:300])

注:res.content返回bytes类型,res.text返回str类型,但编码不匹配。

处理后效果:

37-3.png


打赏码.png


【参考资料】

  1. Requests Developer Interface

  2. Python3中bytes类型转换为str类型

  3. Python字符编码转码之GBK,UTF8互转


群贤毕至

访客