このサンプルでは、キャラクタセットの処理の一つとして使用していますが、 ファイルのダウンロードに使用します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の最新記事】
- Python : Excel の新しいブックのデフォルトのシートのセルに直接値をセットして、オートフィルを Range オブジェクトから実行する
- Python : shift_jis の3列の csv フォーマットのデータを ttk.Treeview に表示する
- Python : ttk.Treeview で表形式を使用して環境変数の一覧表示
- XAMPP + Python( 3.8 ) で WEBアプリの基礎部分構築 : その ( 1 )
- XAMPP + Python( 3.8 ) で WEBアプリの基礎部分構築 : その ( 4 ) : リダイレクトと関数とログ出力
- XAMPP + Python( 3.8 ) で WEBアプリの基礎部分構築 : その ( 3 ) : cgi.FieldStorage() から ディクショナリ
- XAMPP + Python( 3.8 ) でWEBアプリの基礎部分構築 : その ( 2 ) : QUERY_STRING と 画面定義
- Python + MySQL + IFRAME + Bootstrap : 問い合せ WEB アプリテンプレート
- MySQL Connector/Python の使用方法概要のまとめ
- Python3 : 言語的デザインの特徴と要点
- Python ドキュメントに沿った、テキストファイル読み込みの理解
- Python3 でメール送信 ( さくらインターネット )
- Python 3.6 で GET/POST メソッドを想定した CGI 用の簡易テンプレートを作成してみました
- Eclipse + Python(Pydev) : pywin32(COM使用の為) + MySQL Connector/ODBC でループ処理をしながら更新
- Eclipse + Python(Pydev) : MySQL Connector/Python でループ処理をしながら更新
- Pleiades Eclipse 4.7 Oxygen で Python を使って MySQL にアクセスする
- Python 3.4 : インストールと最初にする事( Windows )
- Python3.x : URL を読み出す( bytes から string )
- Python3.1 : クッキーを保持して二つの URL にアクセスする
- Python3.1 : URLを読み出してファイルに出力