首页 > 其他 > 详细

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

时间:2020-12-26 18:11:45      阅读:52      评论:0      收藏:0      [点我收藏+]

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是正常响应

code

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() 

 

 
 
 
 
 
 
 
 
 
 
 

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

原文:https://www.cnblogs.com/sea-stream/p/14192109.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!