我的代码只是抓取一个网页,然后将其转换为Unicode.
html = urllib.urlopen(link).read()
html.encode("utf8","ignore")
self.response.out.write(html)
Run Code Online (Sandbox Code Playgroud)
但我得到一个UnicodeDecodeError:
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 507, in __call__
handler.get(*groups)
File "/Users/greg/clounce/main.py", line 55, in get
html.encode("utf8","ignore")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 2818: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
我认为这意味着HTML包含一些在某处错误形成的Unicode尝试.我可以删除导致问题的任何代码字节而不是出错吗?
可能重复:
如何将ASCII字符串视为unicode并在python中对其中的转义字符进行转换?
如何将unicode转义序列转换为python字符串中的unicode字符
我有一个字符串,其中包含unicode字符,例如\u2026等等.不知何故,我没有收到它unicode,但是收到的是str.如何将其转换回unicode?
>>> a="Hello\u2026"
>>> b=u"Hello\u2026"
>>> print a
Hello\u2026
>>> print b
Hello…
>>> print unicode(a)
Hello\u2026
>>>
Run Code Online (Sandbox Code Playgroud)
所以显然unicode(a)不是答案.那是什么?