python中文乱码解决方案

python中文乱码解决方案

python中文乱码解决方案

最近希望用python抓取一些网页保存在本地,但发现中文乱码现象时有出现。

乱码出现的时机是这样的(python 版本为2.7.10,系统为win8 64位,用IDLE调试程序)

import requests
res=requests.get(….)#某个网址
fp.open(‘xxx.html’,’w’)
fp.write(res.text)
fp.close()

本地文件打开xxx.html后发现中文都是乱码。
网上查了许多资料,都没有解决,最终还是解决了,貌似requests也不是很靠谱,中文编码问题严重。

最终,能够实现用print函数打印的编码是正常的,同时保存为文件的也正常,需要弃用requests而用urllib2

源代码如下

import urllib2  
import sys  
content=urllib2.urlopen(“http://……”).read()  
typeEncode = sys.getfilesystemencoding()  
html = content.decode(“utf-8″).encode(typeEncode)  
soup=BeautifulSoup(html,”lxml”)  
print <span style="color: #ff0000;">soup.prettify()</span>  
fp=open(‘login.html’,’w’)  
fp.write(<span style="color: #ff0000;">content</span>)  
fp.close()  

欢迎评论交流

2015-10-27更新

最近在某网站看到了另一种处理中文字符的方法:
补充如下

# coding:utf-8  
# chardet 需要下载安装
import chardet  
# 抓取网页html  
line = “http://www.***.com”  
 html_1 = urllib2.urlopen(line,timeout=120).read()
# print html_1  
encoding_dict = chardet.detect(html_1)  
# print encoding  
web_encoding = encoding_dict[‘encoding’]  
 if web_encoding == ‘utf-8’ or web_encoding == ‘UTF-8’:
html = html_1  
 else :  
 html = html_1.decode(‘gbk’,’ignore’).encode(‘utf-8’)
# 有以上处理,整个html就不会是乱码。  

发表评论

您的电子邮箱地址不会被公开。

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据