4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TinySeleniumVBAで別タブや別ウィンドウで開かれたEdgeを操作する方法

Posted at

ブラウザをVBAで操作しているときに、別タブや別ウィンドウに遷移してしまうときがあると思います。
そんな時でもVBAから操作し続ける方法を備忘も込めて投稿します。

準備

前回の記事まででTinySeleniumVBAの導入はこちらをご覧ください。

実装

remote-debugging-portを開けた状態でここでは書いていますが、普通に、OpenBrowserした状態でも問題ないです。

検証用にポップアップ表示をするhtml、されるhtmlを作成。
別ウィンドウで表示されたテキストを取得するところまで実装してあります

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>FirstPage</title>
</head>
<body>
  <main>
    <button onclick=test()>ポップアップウィンドウを表示</button>
  </main>
  <script>
    const test = () => {
	  window.open("./popup.html", '_blank', 'width=800, height=600');
    }
  </script>
</body>
</html>
popup.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>PopupPage</title>
</head>
<body>
  <main>
	<span name="span-sample">スパンタグだよ</span>
  </main>
</body>
</html>
Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Sub TinySeleniumNewBrowser()
  Dim driver As New WebDriver
  driver.Edge "hoge\msedgedriver.exe"
  
  Dim cap As Capabilities
  Set cap = driver.CreateCapabilities()
  cap.SetOption "debuggerAddress", "127.0.0.1:9222"
  driver.OpenBrowser cap
  
  ' ポップアップ表示用のhtmlを表示
  driver.Navigate "fuga\index.html"
  ' 表示中のWindowHandleを保持
  Dim currentWindowHandle As String
  currentWindowHandle = driver.Execute(driver.CMD_W3C_GET_CURRENT_WINDOW_HANDLE)
  Sleep "1000"
  
  ' ポップアップウィンドウを表示
  driver.FindElements(By.TagName, "button")(0).Click
  ' WindowHandleのListを取得
  Dim windowHandleList As Object
  Set windowHandleList = driver.Execute(driver.CMD_W3C_GET_WINDOW_HANDLES)

  ' もともと開いていたWindowHandleと異なる場合は新しいWindowHandleを操作対象にする
  Dim windowHandle As Variant
  For Each windowHandle In windowHandleList
    If currentWindowHandle <> windowHandle Then
      Dim params As New Dictionary
      params.Add "handle", windowHandle
      Dim tmp As Object
      Set tmp = driver.Execute(driver.CMD_SWITCH_TO_WINDOW, params)
      Exit For
    End If
    
  Next windowHandle
  Debug.Print driver.FindElements(By.TagName, "span")(0).GetText
  driver.Shutdown
End Sub

適宜、この後はよしなに自動化してください。

答えにたどり着くのに2週間ほどかかってしまった。まだまだ勉強が足りないですね

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?