urllib2.urlopen を使って Shift_JIS でコーディングされたサイトに機種依存文字が含まれていると上手くエンコード出来ない。
凄く嵌って、漸く解決したので覚書。
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# vim: set fileencoding=utf-8 :
import urllib2
url = ‘http://hoge.hogehoge.com’
html = urllib2.urlopen(url).read()
html = html.encode(‘utf-8′)
これだと、機種依存文字の影響で Traceback が出力されます。
Traceback (most recent call last):
File “test.py”, line 8, in ?
html = html.encode(‘utf-8′)
UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0×83 in position 361: ordinal not in range(128)
File “test.py”, line 8, in ?
html = html.encode(‘utf-8′)
UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0×83 in position 361: ordinal not in range(128)
そこで
html = html.encode(‘utf-8′)
を以下に修正。
html = unicode(html, ‘cp932′).encode(‘utf-8′)
cp932 で一端デコードすると良い。
昨日、今日と悩んだ。
融通が利かないところがまた良いカンジがする Python であった、うん。