ラベル Python の投稿を表示しています。 すべての投稿を表示
ラベル Python の投稿を表示しています。 すべての投稿を表示

2012年5月19日土曜日

[Python]CookieとBasic認証を扱うHTTPクライアントの作り方

■概要
CookieとBasic認証を扱うHTTPクライアントが欲しくてPythonでサクッとつくってみました。
※リクエストURLや設定情報を外部ファイルから読み込むようにすると更に使いやすいですが、それは別の機会に。

■実装
Pythonの標準モジュールであるurllib2、cookielibを使用します。
これらのモジュールはPythonのバージョンが2.4以降であれば、問題なく使用できます。

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import os.path, sys

def sendRequest():

    # urllib2をインポートする。
    from urllib2 import urlopen, Request

    # Basic認証の認証情報を設定
    auth_realm = 'realm'
    auth_host = 'host_name'
    auth_id = 'id'
    auth_pw = 'password'

    # cookieの保持情報を設定する。(下記指定ではカレントディレクトリが保存先と)
    COOKIEFILE = 'cookies.lwp'

    # cookielibモジュールの読み込み
    try:

        import cookielib

    except ImportError:

        cookielib = None

    else:

        # 正常に読み込めた場合、LWPCookieJarクラスのインスタンス化。
        cj = cookielib.LWPCookieJar()

    # URLハンドラをセットアップする。
    if cj is not None:

        if os.path.isfile(COOKIEFILE):

            cj.load(COOKIEFILE)

        if cookielib:

            # Basic認証用にHTTPBasicAuthHandlerクラスをインスタンス化し、認証情報を付与する。
            auth_handler = urllib2.HTTPBasicAuthHandler()
            auth_handler.add_password(auth_realm, auth_host, auth_id, auth_pw)

            opener = urllib2.build_opener(auth_handler,urllib2.HTTPCookieProcessor(cj))
            urllib2.install_opener(opener)
        else:
            print "Sorry, can't cookielib."

    # リクエスト情報を設定する。
    theurl = 'http://www.google.com/'
    txdata = None
    txheaders = {'User-agent': 'something_useragent'}

    # リクエスト情報をもとにRequestクラスをインスタンス化し、リクエストを送信する。
    try:
        req = Request(theurl, txdata, txheaders)
        response = urlopen(req)

    # リクエストエラーの場合、エラー情報を出力する。
    except IOError, e:
        print 'Failed to open "%s".' % theurl
        if hasattr(e, 'code'):
            print 'Error code: "%s".' % e.code

    # レスポンスを出力する。
    else:
        print '===== Here are the request of the page. =====\n'
        print str(url) + '\n'

        print '***** Here are the headers of the page. *****\n'
        print str(response.info()) + '\n'

        print '----- Here are the contents of the page. -----\n'
        print str(response.read()) + '\n'

    # Cookieを保存する。
    if cj is None:
        print "Sorry, no cookie jar."
    else:
        print "Here are the cookies received so far:"

        for index, cookie in enumerate(cj):

            print index, ': ', cookie

        cj.save(COOKIEFILE)

    return 0

if __name__ == "__main__":
    sys.exit(sendRequest())
以上です。

参考URL
http://www.python.jp/doc/2.4/lib/module-urllib2.html
http://www.python.jp/doc/2.4/lib/module-cookielib.html
http://www.python.jp/doc/2.4/lib/file-cookie-jar-classes.html

参考文献
Python クックブック 第2版(O'Reilly Japan)




2011年12月20日火曜日

[Python][Mining the Social Web] Graphviz+pygraphvizのインストール

引き続き、「入門ソーシャルデータ」に沿ってデータマイニングに取り組みます。

ソーシャルデータの可視化のために、Graphvizとpygraphvizをインストールします。

Graphviz :DOTという言語出力ファイルを基に、グラフを生成するツールとして有名です。
pygraphviz:pythonを用いて、DOTファイルを生成します。

Mac OSX Lion用のインストールパッケージをダウンロードします。
http://www.graphviz.org/Download_macos.php

パッケージ名:graphviz-2.28.0.pkg

graphviz-2.28.0.pkgをダブルクリックするとインストーラが起動します。
続けるをクリックしていき、インストールを完了します。

次にpygraphvizのインストールです。
例のごとく、easy_installを使用しますが、そのまま実行するとエラーが出ました。

# easy_install pygraphviz
Searching for pygraphviz
Reading http://pypi.python.org/simple/pygraphviz/
Reading http://networkx.lanl.gov/pygraphviz
Reading http://networkx.lanl.gov/download/pygraphviz
Reading http://networkx.lanl.gov/wiki/download
Reading http://networkx.lanl.gov/download
Reading http://sourceforge.net/project/showfiles.php?group_id=122233&package_id=161979
Best match: pygraphviz 1.1
Downloading http://networkx.lanl.gov/download/pygraphviz/pygraphviz-1.1.tar.gz
Processing pygraphviz-1.1.tar.gz
Running pygraphviz-1.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-xlJIBD/pygraphviz-1.1/egg-dist-tmp-qS3unp
Trying pkg-config
/bin/sh: pkg-config: command not found
/bin/sh: pkg-config: command not found
Trying dotneato-config
Failed to find dotneato-config

Your Graphviz installation could not be found.

1) You don't have Graphviz installed:
Install Graphviz (http://graphviz.org)

2) Your Graphviz package might incomplete.
Install the binary development subpackage (e.g. libgraphviz-dev or similar.)

3) You are using Windows
There are no PyGraphviz binary packages for Windows but you might be
able to build it from this source. See
http://networkx.lanl.gov/pygraphviz/reference/faq.html

If you think your installation is correct you will need to manually
change the include_path and library_path variables in setup.py to
point to the correct locations of your graphviz installation.

The current setting of library_path and include_path is:
library_path=None
include_path=None

error: None

パスが通ってないようですが、対処がわかりません。
pipを使用するのはどうかと。

# pip install pygraphviz
Downloading/unpacking pygraphviz
Downloading pygraphviz-1.1.tar.gz (90Kb): 90Kb downloaded
Running setup.py egg_info for package pygraphviz
/bin/sh: pkg-config: command not found
/bin/sh: pkg-config: command not found
Trying pkg-config
Trying dotneato-config
Failed to find dotneato-config

Your Graphviz installation could not be found.

1) You don't have Graphviz installed:
Install Graphviz (http://graphviz.org)

2) Your Graphviz package might incomplete.
Install the binary development subpackage (e.g. libgraphviz-dev or similar.)

3) You are using Windows
There are no PyGraphviz binary packages for Windows but you might be
able to build it from this source. See
http://networkx.lanl.gov/pygraphviz/reference/faq.html

If you think your installation is correct you will need to manually
change the include_path and library_path variables in setup.py to
point to the correct locations of your graphviz installation.

The current setting of library_path and include_path is:
library_path=None
include_path=None

Traceback (most recent call last):
File "", line 14, in
File "/private/var/root/build/pygraphviz/setup.py", line 89, in
raise OSError,"Error locating graphviz."
OSError: Error locating graphviz.
Complete output from command python setup.py egg_info:
/bin/sh: pkg-config: command not found

/bin/sh: pkg-config: command not found

Trying pkg-config

Trying dotneato-config

Failed to find dotneato-config



Your Graphviz installation could not be found.



1) You don't have Graphviz installed:

Install Graphviz (http://graphviz.org)



2) Your Graphviz package might incomplete.

Install the binary development subpackage (e.g. libgraphviz-dev or similar.)



3) You are using Windows

There are no PyGraphviz binary packages for Windows but you might be

able to build it from this source. See

http://networkx.lanl.gov/pygraphviz/reference/faq.html



If you think your installation is correct you will need to manually

change the include_path and library_path variables in setup.py to

point to the correct locations of your graphviz installation.



The current setting of library_path and include_path is:

library_path=None

include_path=None



Traceback (most recent call last):

File "", line 14, in

File "/private/var/root/build/pygraphviz/setup.py", line 89, in

raise OSError,"Error locating graphviz."

OSError: Error locating graphviz.

----------------------------------------
Command python setup.py egg_info failed with error code 1
Storing complete log in /var/root/.pip/pip.log

include_path、library_path variablesについて、graphvizをインストールした場所にパスを通す必要があるようです。
指示通りsetup.pyを編集します。

# OSX, Linux, alternate location
library_path='/usr/local/lib/graphviz'
include_path='/usr/local/include/graphviz'

再度、インストール実行で無事インストールできました。

2011年11月28日月曜日

[Python][Mining the Social Web]Twitter APIを使用してデータを集める

Twitter APIを使用するためのPythonパッケージを追加し、実際にTwitterデータにアクセスしてみる。

$ sudo easy_install twitter
Searching for twitter
Reading http://pypi.python.org/simple/twitter/
Reading http://mike.verdone.ca/twitter/
Best match: twitter 1.7.2
Downloading http://pypi.python.org/packages/source/t/twitter/twitter-1.7.2.tar.gz#md5=a81b512cc8be5ba278bdaceb6d988fe6
Processing twitter-1.7.2.tar.gz
Running twitter-1.7.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-1iZuPg/twitter-1.7.2/egg-dist-tmp-7cd07T
Adding twitter 1.7.2 to easy-install.pth file
Installing twitter-stream-example script to /usr/local/bin
Installing twitter script to /usr/local/bin
Installing twitterbot script to /usr/local/bin
Installing twitter-log script to /usr/local/bin


Installed /Library/Python/2.7/site-packages/twitter-1.7.2-py2.7.egg
Processing dependencies for twitter
Finished processing dependencies for twitter


パッケージドキュメントを読むためにはpydocを実行する。
*nix : pydoc twitter.Twitter
(Windows : python -mpydoc twitter.Twitter)

TwitterのトレンドAPIを実行してみるが、エラー発生。
$ python
Python 2.7.1 (r271:86832, Jun 25 2011, 05:09:01)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import twitter
>>> twitter_api = twitter.Twitter(domain="api.twitter.com", api_version='1')
>>> trends = twitter_api.trends()
Traceback (most recent call last):
File "", line 1, in
File "build/bdist.macosx-10.7-intel/egg/twitter/api.py", line 165, in __call__
File "build/bdist.macosx-10.7-intel/egg/twitter/api.py", line 180, in _handle_response
twitter.api.TwitterHTTPError: Twitter sent status 404 for URL: 1/trends.json using parameters: ()
details:

はて、404エラー出てるな。
とりあえず、本文に記載のURL:http://search.twitter.com/1/trends.jsonを入力してみるがこちらもエラー。
よく見ると、このURLってhttp指定してるけど、Twitterってhttps使うように変わったような...

と、いうことでTwitter API のドキュメントを確認してみる。
https://dev.twitter.com/docs/api/1/get/trends/%3Awoeid

やっぱり、API仕様変わってますね。ということで、モジュール修正が必要だな。

[Python][Mining the Social Web] easy_installでモジュール追加

Mining the Social Web(オライリー刊)を参考に分析を進めていくための準備

Pythonでモジュール管理はeasy_installを使用するのがベター。
Macでも変わらない。

NetworkXモジュールはグラフを作り、分析し、類似する出力を観察するために使用するようだ。
$ sudo easy_install networkx
Searching for networkx
Reading http://pypi.python.org/simple/networkx/
Reading http://networkx.lanl.gov/
Reading http://networkx.lanl.gov/download/networkx
Reading http://sourceforge.net/project/showfiles.php?group_id=122233
Reading https://networkx.lanl.gov
Reading http://networkx.lanl.gov/download
Reading http://networkx.lanl.gov
Best match: networkx 1.6
Downloading http://networkx.lanl.gov/download/networkx/networkx-1.6-py2.7.egg
Processing networkx-1.6-py2.7.egg
creating /Library/Python/2.7/site-packages/networkx-1.6-py2.7.egg
Extracting networkx-1.6-py2.7.egg to /Library/Python/2.7/site-packages
Adding networkx 1.6 to easy-install.pth file

Installed /Library/Python/2.7/site-packages/networkx-1.6-py2.7.egg
Processing dependencies for networkx
Finished processing dependencies for networkx

Numpyは科学計算用ツール。NetworkXが依存関係にある。
$ sudo easy_install numpy
Searching for numpy
Best match: numpy 1.5.1
Adding numpy 1.5.1 to easy-install.pth file

Using /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python
Processing dependencies for numpy
Finished processing dependencies for numpy

NoseはPythonのテストツール
$ sudo easy_install nose
Searching for nose
Reading http://pypi.python.org/simple/nose/
Reading http://somethingaboutorange.com/mrl/projects/nose/
Reading http://readthedocs.org/docs/nose/
Best match: nose 1.1.2
Downloading http://pypi.python.org/packages/source/n/nose/nose-1.1.2.tar.gz#md5=144f237b615e23f21f6a50b2183aa817
Processing nose-1.1.2.tar.gz
Running nose-1.1.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-UusYYV/nose-1.1.2/egg-dist-tmp-UafvfE
Adding nose 1.1.2 to easy-install.pth file
Installing nosetests script to /usr/local/bin
Installing nosetests-2.7 script to /usr/local/bin

Installed /Library/Python/2.7/site-packages/nose-1.1.2-py2.7.egg
Processing dependencies for nose
Finished processing dependencies for nose


以上です。