Pythonでスクレイピングしたい
例えば、SJISのサイトをスクレイピングして、UTF-8で出力とか文字コード周りが全然分かってなくてハマった。
どうもPython内部ではUnicodeで処理してるので、一旦Unicodeに変換(decode)してから、UTF-8に変換(encode)するという事らしい。
#!/usr/local/bin/python # -*- coding: utf-8 -*- import urllib2 url = "http://hoge.hoge" contents = urllib2.urlopen(url, "rb").read().decode("shift_jis").encode("utf-8")
なるほどなぁ。