トップページ > Selenium API(逆引き) > 【Ruby】click_and_hold/move_by/perform

【Ruby】click_and_hold/move_by/perform・・・要素を特定座標にドラッグする

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

「click_and_hold」「move_by」「perform」を連続で実行することで要素を特定座標にドラッグすることが出来ます。

下記サンプルでは、まず指定した要素をドラッグする「click_and_hold」を実行しています。このメソッドは引数に指定した要素をクリックし、そのままドラッグ状態にします。続いて指定座標にマウスカーソルを移動させる「move_by」。このメソッドは、引数に現在のマウスカーソル位置からのオフセット(X/Y座標)を指定していきます。つまり、ドラッグしながらマウスカーソル移動をしていることになります。もし、移動した後にドロップしたい場合は「move_by」の後に「release」メソッドを追加します。そして最後に「perform」を実行することで、これまでのメソッドをビルドした後、実行していきます。

※アクションについてはこちら

説明

◆メソッド
  ・click_and_hold(element)           :要素を指定してドラッグ
  ・move_by(xOffset,yOffset)                 :オフセット指定してマウスカーソル移動
  ・perform                     :処理の実行
◆使用形態
  ・driver.action.click_and_hold(element).
                  move_by(xOffset,yOffset).
                  perform  
◆備考
  ・ドロップ操作をする場合は"release"を追加する
◆関連項目
  ・要素を他の要素へドラッグする
  ・要素を他の要素へドラッグ&ドロップする

サンプル

require 'selenium-webdriver'
 
# Firefoxを起動
driver = Selenium::WebDriver.for(:firefox)
#指定したURLに遷移する
driver.get('https://jqueryui.com/draggable/')
#要素がロードされるまでの待ち時間を30秒に設定
driver.manage.timeouts.implicit_wait = 30
#ドラッグ対象の要素が存在するフレームに切り替える
driver.switch_to.frame(0)
#IDが"draggable"の要素を取得(ドラッグ対象の要素)
element = driver.find_element(:id, 'draggable')
#3秒間待機して移動前の位置を確認
sleep(3)
#要素をドラッグした状態でX/Y方向に100ポイントカーソル移動させる
driver.action.click_and_hold(element).
              move_by(100, 100).
              perform
※selenium version 4.1.0で動作確認をしています(ブラウザのUIや属性値などが変更された場合、実行結果が異なる可能性があります)

実行結果

clickAndHold
yajirushi
clickAndHold2

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: (404) <!DOCTYPE html> <html lang=en> <meta charset=utf-8> <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width"> <title>Error 404 (Not Found)!!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/googlelogo_c in /home/users/1/monda-muki/web/seleniumqref.com/google-api-php-client-1-master/src/Google/Http/REST.php on line 110