ふにゃるんv2

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

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とかに突入している訳じゃないって事です。