TIM*_*MEX 1 python unicode encode http urllib2
theurl = 'http://bit.ly/6IcCtf/'
urlReq = urllib2.Request(theurl)
urlReq.add_header('User-Agent',random.choice(agents))
urlResponse = urllib2.urlopen(urlReq)
htmlSource = urlResponse.read()
if unicode == 1:
#print urlResponse.headers['content-type']
#encoding=urlResponse.headers['content-type'].split('charset=')[-1]
#htmlSource = unicode(htmlSource, encoding)
htmlSource = htmlSource.encode('utf8')
return htmlSource
Run Code Online (Sandbox Code Playgroud)
请看一下unicode部分.我尝试了这两个选项......但是没有用.
htmlSource = htmlSource.encode('utf8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 370747: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
当我尝试更长的编码方法时...
_mysql_exceptions.Warning: Incorrect string value: '\xE7\xB9\x81\xE9\xAB\x94...' for column 'html' at row 1
Run Code Online (Sandbox Code Playgroud)
您的html数据是来自已经使用某种编码编码的互联网的字符串.在对其进行编码之前utf-8,必须先对其进行解码.
Python 试图解码它是不明智的(这就是为什么你得到的UnicodeDecodeError不是UnicodeEncodeError).
在尝试重新编码之前,您可以通过明确解码字节字符串(使用适当的编码)来解决问题.utf-8
例:
utf8encoded = htmlSource.decode('some_encoding').encode('utf-8')
Run Code Online (Sandbox Code Playgroud)
使用正确的编码页面编码在第一位,而不是'some_encoding'.
在解码之前,您必须知道字符串正在使用哪种编码.
| 归档时间: |
|
| 查看次数: |
384 次 |
| 最近记录: |