BeautifulSoup4 print() 输出中文乱码解决方法

import  requests
from bs4 import BeautifulSoup  #pip install beautifulsoup4

'''
BeautifulSoup 输出中文 => print cmd 默认编码是 Codepage 936
https://www.baidu.com/ 网页编码是 uft-8
导致 print() 输出乱码
解决方法:
让 r.encoding = 'gbk2312'; 编码为 gbk 此时输出正常.
'''

#你可以找出 Requests 使用了什么编码,并且能够使用 r.encoding 属性来改变它
r= requests.get('https://www.baidu.com/');
r.encoding = 'gbk2312';
soup=BeautifulSoup(r.text,"html.parser") 

print(soup.title);

#写入到文件.
fo = open('ttt.txt', "w")        
fo.write(('\r' +soup.title.string + '\r\n'))  
fo.close()       

 

 

urllib.request 返回的数据需要解码,如 网站返回的是GBK编码数据. 需要调用decode("gbk") 此时输出不会乱码.

 

        with urllib.request.urlopen(url, context=context) as response:
            html = response.read()
            html=html.decode("gbk")
            print(html);
            print(response.code())#200是正常响应

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值