初めてのIE操作(6)~InternetExplorerオブジェクトのDocumentプロパティを調べるFunction
InternetExplorerオブジェクトのDocumentプロパティの返り値を確認するFunction
前回
の「問題点」の項にも書いたとおり、VBAからIEを操ったときに、画面に表示されているHTMLドキュメントと、InternetExplorer
オブジェクトのDocument
プロパティが返すHTMLDocument
オブジェクトの内容が異なる、というわけのわからない現象がたまに起きる。
ということは、InternetExplorer
オブジェクトがどのような状態にあるのかを確認する工程が必要だと言うことになる。
HTMLDocumentオブジェクトのTitleプロパティを調べるFunction
簡単なFunction
を作る。
リスト1 標準モジュール
Public Function isTargetPage(ByVal targetDocument As HTMLDocument, _ ByVal pageTitleKeyWord) As Boolean isTargetPage = True If InStr(1, targetDocument.Title, pageTitleKeyWord) > 0 _ Then Exit Function isTargetPage = False End Function
アホみたいに簡単なコード。
引数としてHTMLDocument
オブジェクト(InternetExplorer
オブジェクトのDocument
プロパティの返り値)と、タイトルのキーワード文字列を受け取って、Instr
関数によってHTMLDocument.Title
プロパティを調べているだけ。
使ってみる
次のようなコードで実験。
リスト2 標準モジュール
Public Sub testIsTargetPage() Dim targetIE As New InternetExplorer With targetIE .Visible = True Call .Navigate("http://akashi-keirin.hatenablog.com/entry/2018/12/16/001606") Do While .Busy Or _ .ReadyState <> READYSTATE_COMPLETE DoEvents Loop End With Dim targetTextBox As Object Set targetTextBox = getElementByTagAndKeyWord(targetIE, "input", "name=""q""") targetTextBox.Value = "ち~んw" Dim targetButton As Object Set targetButton = getElementByTagAndKeyWord(targetIE, "input", "value=""検索""") targetButton.Click Debug.Print isTargetPage(targetIE.Document, "ち~んw") '……(*)' Debug.Print targetIE.Document.Title End Sub
実行時は、(*)の行にブレークポイントを設定して、ページ移動を待つことにする。
IEが起動し、検索ボックスに「ち~んw
」が書き込まれ、ページが移動する。
十分に待って、完全にページが表示されたとおぼしき
この状態で満を持してコードの実行を再開。
ガックリ。
おわりに
実は、毎回このようになるわけではなく、ちゃんと移動後のページが取得できている場合もあるから悩ましい。
たとえば、上掲コードの(*)の前に
Call WindowsAPI.waitFor(20000)
を入れて、Click
メソッド実行後に20秒(!)待機させるようにして5回実験すると、2回成功、3回失敗、という何とも不安定な結果だった。
やっぱりわけがわからないなあ。