トップページ > Selenium API(逆引き) > 【Ruby】window_handle

【Ruby】window_handle・・・ウインドウハンドルを取得する

【PR】業界トップクラスの「高単価報酬」「低マージン」を実現!レバテックフリーランス

「window_handle」実行でウインドウハンドルを取得できます。

ウインドウハンドルとはウインドウ(ブラウザ)を識別する為の識別情報です。Seleniumでは、このウインドウハンドル使ってウインドウやフレームを切り替えることが出来ます。具体的にはswitch_to.window(xxx)でxxxの部分にウインドウハンドルを指定することで制御対象とするウインドウの切り替えを行います。

「window_handle」と同じくウインドウハンドルを取得するメソッドに「window_handles」がありますが、前者はカレントウインドウ(制御対象になっているウインドウ)のみのハンドルを取得するのに対し、後者はカレントセッション(指定したインスタンス)全てのハンドルを取得するという違いがあります。

説明

◆メソッド
  ・window_handle
◆使用形態
  ・driver.window_handle
◆備考
  ・指定したインスタンスでカレントウインドウのハンドルのみを取得する
◆関連項目
  ・複数のウインドウハンドルを取得する
  ・全てのクッキーを取得する

サンプル

require 'selenium-webdriver'

# Firefoxを起動
driver = Selenium::WebDriver.for(:firefox)
# Googleページに移行
driver.get('https://www.google.co.jp/')
#カレントページのソースコードを取得して表示
print(driver.window_handle)
※selenium version 4.1.0で動作確認をしています

実行結果

1193269870
※ここで設定されているウインドウハンドルの内容は架空の値です

動画デモ

※字幕をONにすると解説のテロップが表示されます※


Fatal error: Uncaught Google_Service_Exception: Error calling GET https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A138132118&start-date=7daysAgo&end-date=yesterday&metrics=ga%3Apageviews&dimensions=ga%3ApageTitle%2C+ga%3ApagePath&sort=-ga%3Apageviews&max-results=1000: (502) <!DOCTYPE html> <html lang=en> <meta charset=utf-8> <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width"> <title>Error 502 (Server Error)!!1</title> <style> *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelog in /home/users/1/monda-muki/web/seleniumqref.com/google-api-php-client-1-master/src/Google/Http/REST.php on line 110