Python/HTTP
提供:やる気向上作戦
HTTP
HTTPでデータを読み込む (gzip対応)
参考: http://www.diveintopython.org/http_web_services/gzip_compression.html
import urllib2, gzip, socket, StringIO
# ソケットタイムアウト時間を設定
socket.setdefaulttimeout(30)
# リクエストオブジェクトを構築
req = urllib2.Request('http://example.com/')
# ヘッダを追加
req.add_header('Accept-encoding', 'gzip')
req.add_header('User-agent', 'MyUserAgent (+http://example.com/robot.html)')
# リクエストを送信し、レスポンスを読み出すためのファイルライクなオブジェクトを得る
opener = urllib2.build_opener()
f = opener.open(req)
data = f.read()
f.close()
compressed = False
if (f.headers.has_key('Content-encoding')):
contentEncoding = f.headers['Content-encoding']
if (contentEncoding.strip().lower() == 'gzip'):
compressed = True
if (compressed):
sf = StringIO.StringIO(data)
dec = gzip.GzipFile(fileobj=sf)
data = dec.read()
# ここでdataは、圧縮を解除されたメッセージボディ
fを直接GzipFileでラップしないのは、GzipFileがtell()を要求するため。urllib2の返すファイルライクオブジェクトは、tell()を実装していない。