私のコードは、Web ページをスクレイピングして、それを Unicode に変換するだけです。
html = urllib.urlopen(link).read()
html.encode("utf8","ignore")
self.response.out.write(html)
しかし、私は次のことを得ます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)
これは、HTML のどこかに、誤って作成された Unicode の試みが含まれていることを意味していると思います。エラーが発生する代わりに、問題の原因となっているコード バイトを削除するだけでよいですか?
ベストアンサー1
>>> u'aあä'.encode('ascii', 'ignore')
'a'
meta
応答内の適切なタグまたはヘッダー内の文字セットを使用して、返された文字列をデコードしContent-Type
、エンコードします。
メソッドencode(encoding, errors)
は、エラーのカスタム ハンドラを受け入れます。 の他に、デフォルト値は次のとおりignore
です。
>>> u'aあä'.encode('ascii', 'replace')
b'a??'
>>> u'aあä'.encode('ascii', 'xmlcharrefreplace')
b'aあä'
>>> u'aあä'.encode('ascii', 'backslashreplace')
b'a\\u3042\\xe4'
見るhttps://docs.python.org/3/library/stdtypes.html#str.encode