网站首页 美食营养 游戏数码 手工爱好 生活家居 健康养生 运动户外 职场理财 情感交际 母婴教育 时尚美容

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

时间:2024-10-12 12:50:07

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

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

2、打开Python开发工具IDLE,新建‘request.py’文件,并写代码如下:import requestsr = 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’不会乱码,我们打印R髫潋啜缅esponse r 的编码。代码如下:import requestsr = requests.get('http://www.baidu.com/')print (type(r))print (r.encoding)print (r.text)

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

5、F5运行程序,打印出:ISO-8859-1为其胆咣骜岱编码方式,这就是问题所在,继续改写代码如下:import requestsr = 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包请求网页乱码解决方法
© 2025 五度知识库
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com