SQLの窓

2010年06月21日


Python3.1 : URLを読み出して、バイナリのままファイル出力する

このサンプルでは、キャラクタセットの処理の一つとして使用していますが、
ファイルのダウンロードに使用します
0005.py ( utf8n )
#! /usr/bin/env python3.1

import urllib.request
import http.cookiejar

# Cookie handling for HTTP clients
# python312.chm::/library/http.cookiejar.html
cj = http.cookiejar.MozillaCookieJar()
opener = urllib.request.build_opener(
			urllib.request.HTTPCookieProcessor( cj )
		 )

# 最初の呼び出し
# ※ cookiejar を設定した opener で読みだす
try:
	print( "このヘッダーが送られます :" , opener.addheaders, end="\n\n" )
	response = opener.open("http://localhost/web/test/sv1.php")

# URL 関係のエラー処理
except urllib.error.URLError as e:
	print(e)
	exit()
# 一般のエラー処理
except Exception as e:
	print(e)
	exit()

# サーバーからの http ヘッダ
print( response.info() )

# バイナリとしての HTML ページを取得
html = response.read()

# html の キャラクタセット に合わせて decode して
# 文字列として取り込む
html_shift_jis = html.decode("shift_jis")

# そのまま、コマンドプロンプトへ出力
print( "-------------------------------------------------" )
print( html_shift_jis )
print( "-------------------------------------------------" )

# キャラクタセットを変換して出力
# ※ テキストのみ
print( html_shift_jis, file=open("html_shift_jis.txt","wt") )
print( html_shift_jis, file=open("html_euc_jp.txt","wt", encoding="euc_jp") )
# utf8n で出力されました
print( html_shift_jis, file=open("html_utf_8.txt","wt", encoding="utf_8") )

# バイナリの表示
print( "-------------------------------------------------" )
print( html )
print( "-------------------------------------------------" )

# バイナリのまま保存
# ※ キャラクタセットが解らない場合のファイル化
html_org = open("html_org.txt", mode='wb') 
html_org.write( html )

# クッキーを保存
# ※ cj.load( "ファイルのパス" ) が可能です
cj.save( "cookie_100621.sav", ignore_discard=True, ignore_expires=True )
Python3.1 マニュアル
The Python Standard Library ≫ 20. Internet Protocols and Support
20.22.2. FileCookieJar subclasses and co-operation with web browsers

The Python Standard Library ≫ 7. String Services ≫
7.6.3. Standard Encodings


【Pythonの最新記事】
posted by lightbox at 2010-06-21 16:08 | Python | このブログの読者になる | 更新情報をチェックする
container 終わり



フリーフォントで簡単ロゴ作成
フリーフォントでボタン素材作成
フリーフォントで吹き出し画像作成
フリーフォントではんこ画像作成
ほぼ自由に利用できるフリーフォント
フリーフォントの書体見本とサンプル
画像を大きく見る為のウインドウを開くボタンの作成

CSS ドロップシャドウの参考デモ
イラストAC
ぱくたそ
写真素材 足成
フリーフォント一覧
utf8 文字ツール
右サイド 終わり
base 終わり