Python使用request包请求网页乱码解决方法

 时间:2026-02-14 04:17:27

1、先安装requests包,打开电脑运行输入‘cmd’,在命令行窗口输入

‘pip install requests’

Python使用request包请求网页乱码解决方法

2、打开Python开发工具IDLE,新建‘request.py’文件,并写代码如下:

import requests

r = requests.get('http://www.baidu.com')

print (type(r))

print (r.text)

Python使用request包请求网页乱码解决方法

3、F5运行程序,打印出信息如图。r = requests.get('http://www.baidu.com'),

r是requests.models.Response的对象。r.text是其网页内容。

Python使用request包请求网页乱码解决方法

4、这里有乱码,查看网页发现charset的编码是‘utf-8’,但是‘utf-8’不会乱码,我们打印Response r 的编码。代码如下:

import requests

r = requests.get('http://www.baidu.com/')

print (type(r))

print (r.encoding)

print (r.text)

Python使用request包请求网页乱码解决方法

5、F5运行程序,打印出:ISO-8859-1为其编码方式,这就是问题所在,继续改写代码如下:

import requests

r = requests.get('http://www.baidu.com/')

print (type(r))

print (r.encoding)

print (r.apparent_encoding)

print ((r.text.encode(r.encoding).decode(r.apparent_encoding)))

r.apparent_encoding是通过内容分析出的编码,这里是utf8编码

Python使用request包请求网页乱码解决方法

Python使用request包请求网页乱码解决方法

6、F5运行程序,网页内容没有乱码了,通过r.apparent_encoding即utf-8解码就行了。一般网页通过这种方式都能解码正常

Python使用request包请求网页乱码解决方法

  • 阴阳师怎样式神委派
  • Word窗口图标变得很大很模糊怎么办
  • mysql增删改查语句适合初学者
  • 如何增加ASMR视频的播放量或直播的围观人数?
  • 串口屏控件说明—如何使用滑块控件
  • 热门搜索
    仓鼠怎么分辨公母 皮肤不好怎么改善 页眉怎么删除 怎么美白 宝贝不大怎么让你舒服 壳牌机油怎么样 披萨怎么做 小孩牙痛怎么快速止痛 装修贷款怎么申请 大龙虾怎么做好吃