漫ろで行こう

自由気まま過ぎる、ギークになりたい男の子の話

urllib2.urlopen を使って Shift_JIS でコーディングされたサイトに機種依存文字が含まれていると上手くエンコード出来ない。
凄く嵌って、漸く解決したので覚書。

#!/usr/bin/env python
# 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)

そこで

html = html.encode(‘utf-8′)

を以下に修正。

html = unicode(html, ‘cp932′).encode(‘utf-8′)

cp932 で一端デコードすると良い。
昨日、今日と悩んだ。

融通が利かないところがまた良いカンジがする Python であった、うん。

Related Posts

  1. [言語][Python]RSS 作成モジュール PyRSS2Gen のインストールと UTF-8 での保存方法
  2. [言語][Python]tinyurl.com で URL 短縮
  3. [言語][Python][メモ]CORESERVER に Python 2.5 をインストール
  4. [言語][Python][メモ]レンタルサーバーで Python 追加モジュールのインストール
このエントリーをはてなブックマーク この記事をクリップ! このエントリーをdel.icio.usに追加

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Proudly powered by WordPress. Theme developed with WordPress Theme Generator.
Copyright © 漫ろで行こう. All rights reserved.