ふにゃるんv2

もとは、http://d.hatena.ne.jp/Wacky/

PythonからActiveXを使ってIEを操作する例

気付いたら、先週は何もブログしてなかったよ。あふ。

という訳で(何が?)、PythonからActiveXを使ってIEを操作する例です。
適当なWeb siteを表示し、その中のテーブル内の要素を表示しています。

#!/bin/env python
# -*- encoding: shift-jis -*-
import sys
import os
import re
import win32com.client

def http_open(ie, url):
    ie.Navigate(url)
    while ie.ReadyState != 4:
        print "HTTP access...", ie.ReadyState
    print "Http Complete!!"

def main():
    ie = win32com.client.Dispatch("InternetExplorer.Application")
    ie.Visible = True
    
    http_open(ie, "http://www.google.com/")
    
    doc = ie.Document
    for tbl in doc.all.tags("TABLE"):
        print "$$$ TABLE!!"
        y = 0
        for row in tbl.rows:
            x = 0
            for cell in row.cells:
                print x, y, cell.innerText
                
                x = x + 1
            y = y + 1
    
    print "table 巡回終了"
    ie.Quit()

if __name__ == "__main__":
    ret = main()

実行結果例:

HTTP access... 3
HTTP access... 3
HTTP access... 3
HTTP access... 3
HTTP access... 4
Http Complete!!
$$$ TABLE!!
0 0 パーソナライズド ホーム | ログイン
0 1
$$$ TABLE!!
0 0 ウェブ    イメージ    ニュース    ローカルNew!    グループ    more ≫
$$$ TABLE!!
0 0
1 0
2 0   検索オプション
  表示設定
  言語ツール
0 1 ウェブ全体から検索日本語のページを検索
table 巡回終了

ActiveXの制御だと、デバッグしやすいVBが一番楽なんですが、テキスト処理と連携させようとすると、Pythonなどが選択肢に上がってくると思います。
(元は、VBで骨格を作って、Pythonに移植って形を取ってます)


コード中、テーブル内の各セルの位置が取ってこれないので、x, y変数を宣言してループを回して暫定的なインデックスとして処理しています。
TD要素にインデックス位置を取得するプロパティがあると嬉しいんですけどねぇ。(自分で調べた限りでは見つからなかったです)


余談ですが、innerTextで取ってくる文字列はUnicodeなので、比較する場合、「u"ほげ"」という具合にする必要があるみたいです。

PythonからActiveXを使ってExcelとIEを操作する例

お次は、IEで とあるWebページを表示させ、テーブルの内容をExcelに貼り付けてみましょう。


以下の例では、Yahoo!ノベルズランキングのページのデータ部分をExcelに取り込んでいます。

#!/bin/env python
# -*- encoding: shift-jis -*-
import sys
import os
import re
import win32com.client

def http_open(ie, url):
    ie.Navigate(url)
    while ie.ReadyState != 4:
        print "HTTP access...", ie.ReadyState
    print "Http Complete!!"

def main():
    ie = win32com.client.Dispatch("InternetExplorer.Application")
    ie.Visible = True
    
    excel = win32com.client.Dispatch("Excel.Application")
    excel.Visible = True
    book = excel.Workbooks.Add()
    sheet = book.Worksheets.Item(1)
    
    http_open(ie, "http://headlines.yahoo.co.jp/ranking/php/book/d.html")
    
    isPaste = False
    doc = ie.Document
    for tbl in doc.all.tags("TABLE"):
        print "$$$ TABLE!!"
        y = 0
        for row in tbl.rows:
            x = 0
            for cell in row.cells:
                v = cell.innerText
                print x, y, v
                if v == u"順位":
                    isPaste = True
                if v.find(u"前日までのランキング") >= 0:
                    isPaste = False
                if isPaste:
                    sheet.Cells(y+1, x+1).Value = v
                
                x = x + 1
            y = y + 1
    
    print "table 巡回終了"
    ie.Quit()

if __name__ == "__main__":
    ret = main()


実行例:
ExcelとIE
ExcelとIE posted from フォト蔵


ちなみに何でこんなコードを作ったのかというと、主に以下の困難に突き当たったからです。

  • とあるデータが欲しい。
  • そのデータは、Webページを1枚ずつめくっていけば閲覧できる。
  • データを流用したいが、しこしこ手でコピペするのもアホらしい。
    (Excelに取り込むって手もあるんですけど、大抵楽しい装飾がかかったり、元のテーブルが技巧を凝らしているので楽しい配置になったりするんですよね)

まぁ世の中、全てがWeb2.0とかに突入している訳じゃないって事です。