UnicodeEncodeError的问题,求救啊,已经百度google过,还是有问题

lasttry 2012-01-23 05:24:32
运行环境:vps centos 6.0

使用putty远程ssh运行显示:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 190-277: ordinal not in range(128)

使用liux远程ssh运行
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 190-277: ordinal not in range(128)


#coding:utf-8

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import urllib2
import chardet

def getWebContent2(url):
print(url)
req = urllib2.urlopen(url, timeout=20)
content=req.read()
print("code:"+chardet.detect(content)['encoding'])
print(content)
if chardet.detect(content)['encoding']=='ISO-8859-2':
ucontent = unicode(content,'utf-8')
else:
ucontent = unicode(content,chardet.detect(content)['encoding'],'replace')
return ucontent

if __name__=="__main__":
print("Debug:test qs_getweb.py")
url="hao123.com"
response = getWebContent2("http://www.%s" % url)
print(response)
...全文
493 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
黄哥Python培训 2012-01-26
  • 打赏
  • 举报
回复
你先没有说你用的是python 2.7 还是python3.2
python2.7和python3.2下编码完全不一样。
我在python 2.7 下运行你的代码,根本不运行,连错误都不包。
我在pyton2.7+winxp 下修改可以运行的代码,供参考。

#coding:utf-8


import urllib2
import chardet

def getWebContent2(url):
print(url)
req = urllib2.urlopen(url, timeout=40)
content=req.read()
mychar=chardet.detect(content)
#print mychar
bianma=mychar['encoding']
if bianma == 'utf-8' or bianma == 'UTF-8':
#html=html.decode('utf-8','ignore').encode('utf-8')
ucontent=content
else :
#看hao123编码是gbk
ucontent=content.decode('gbk','ignore').encode('utf-8')
#html =html.decode('gb2312').encode('utf-8')


return ucontent

if __name__=="__main__":
print("Debug:test qs_getweb.py")
#url="hao123.com"
#response = getWebContent2("http://www.%s" % url)
response = getWebContent2("http://www.hao123.com")
print(response)

强天放 2012-01-25
  • 打赏
  • 举报
回复
export LANG=en_US.UTF-8
lasttry 2012-01-23
  • 打赏
  • 举报
回复
[root@server1 code]# python qs_getweb.py
Debug:test qs_getweb.py
http://www.hao123.com
code:GB2312
Traceback (most recent call last):
File "qs_getweb.py", line 49, in <module>
print(response)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 190-277: ordinal not in range(128)
iambic 2012-01-23
  • 打赏
  • 举报
回复
贴完整的错误信息。连第几行python代码出错都不知道,还看个鬼。

37,742

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧