みーのぺーじ

みーが趣味でやっているPCやソフトウェアについて.Python, Javascript, Processing, Unityなど.

Pythonのurllib.requestにてCookieを利用する

Pythonのurllib.requestにて,Cookieを利用する方法をメモしておきます.http.cookiejarを利用します.以下,Python3.3で検証しました.

以下のスプリクトは,Cookieが有効な状態で指定されたurlにアクセスし,ファイルをダウンロードします.

import urllib.request
import http.cookiejar
import gzip
import sys,os,os.path

class Main():
    def __init__(self):
        self.cookiefile = "cookies.txt"
        self.cj = http.cookiejar.LWPCookieJar()
        if os.path.exists(self.cookiefile):
            self.cj.load(self.cookiefile)
        opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cj))
        urllib.request.install_opener(opener)
    
    def __del__( self ):
        self.cj.save(self.cookiefile)
        print("Cookie saved to "+self.cookiefile)
        
    def getURL(self,url):
        headers = { "User-Agent" :  "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)" }
        req = urllib.request.Request(url, None, headers)
        response = urllib.request.urlopen(req)
        charset = response.headers.get_content_charset()
        if charset==None:
            charset = "utf-8"
        #print(charset)
        dechtml = ""
        if response.info().get("Content-Encoding")=="gzip":
            dechtml = gzip.decompress(response.read())
        else:
            dechtml = response.read()
        html = dechtml.decode(charset,"ignore")
        open("response}.html","w",encoding=charset,errors="ignore").write(html)
        return
    
Main().getURL("http://www.google.com")

まず,__init__(self)で,cookies.txtというファイルがあれば読み込み,http.cookiejar.LWPCookieJar() にロードしてurllib.request.HTTPCookieProcessorに指定します.できたopenerをurllib.requestにinstallします.

__def__(self)では,プログラムの終了時にcookies.txtにhttp.cookiejar.LWPCookieJar()の情報を書き込みます.これで次回アクセスする時にもクッキーが保存されます.

あとは普通にurlopen()するだけですが,gzipでエンコードされるケースにも対応させました.response.info().get("Content-Encoding")でエンコードを取得し,もしもgzipだったら,gzip.decompressを使って解凍しています.

これを実行すると,同じディレクトリにcookies.txtが作成され,www.google.comにアクセスした場合は例えば以下のようになります.

#LWP-Cookies-2.0
Set-Cookie3: NID="67=BAEsnpSjm6zOzIhejErpz52KstRi0mntQH0K2SRXUP--XPraxdeNx5z4g-P4_NFOZJSoEd3biDHkclPaMy1ksIaNbWu2CY6ObRZTPJPY5DKXVYm220ReRrVMBPFfDosd"; path="/"; domain=".google.co.jp"; path_spec; domain_dot; expires="2014-06-05 17:14:46Z"; HttpOnly=None; version=0
Set-Cookie3: PREF="ID=55053090210ea62c:FF=0:TM=1386177286:LM=1386177286:S=p8SXypM3GudtvyN2"; path="/"; domain=".google.co.jp"; path_spec; domain_dot; expires="2015-12-04 17:14:46Z"; version=0
Set-Cookie3: NID="67=qMpfiMsLqAWSqAerxtOeVzNUxke78b8f2gXir-vhqcQIxh8jIAaKng3IikoU--i4sMU5mk2gWHhbZZrteG8xb4r795n3b3n2D48QEzqRbn5hK_aJ6-BqJzjpS8U7Qk"; path="/"; domain=".google.com"; path_spec; domain_dot; expires="2014-06-05 17:14:46Z"; HttpOnly=None; version=0
Set-Cookie3: PREF="ID=ce7dae6aeb8ee40d:FF=0:TM=1386177286:LM=1386177286:S=VpTreEFf0ihLMlnt"; path="/"; domain=".google.com"; path_spec; domain_dot; expires="2015-12-04 17:14:46Z"; version=0

クッキーがどうなっているのかは,これを見れば一発で分かるかと思います.

Pythonスクリプトでもこれぐらい頑張れば普通のブラウザと遜色なくサイトにアクセスできると思います.

<参考>