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

【Ruby】location・・・要素の(X,Y)座標を取得する

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

要素に対して「location」を実行することで要素の(X,Y)座標を取得することが出来ます。

下記のサンプルでは、まずGoogleトップページに存在する検索ボタンへの要素を取得しています。そして、その要素に対して「location」を実行することで、要素の(X,Y)座標を取得しています。ここで要素の座標取得位置ですが、要素の左上隅の座標を取得していきます。また、要素の座標はウインドウ位置に影響されることはなく、ウインドウがどの位置にどういったサイズで存在しようと影響はうけず一定の座標を取得することが出来ます。

説明

◆メソッド
  ・location
◆使用形態
  ・element.location
◆備考
  ・要素の左上隅(X,Y)座標を取得する
◆関連項目
  ・セレクトタグに含まれるオプションを取得する
  ・セレクトタグの選択されているオプションを取得する

サンプル

require 'selenium-webdriver'
 
# Firefoxを起動
driver = Selenium::WebDriver.for(:firefox)
#指定したURLに遷移する
driver.get('https://www.google.co.jp')
#検索ボタンの要素をname属性名から取得
element = driver.find_element(:name,'btnK')
#検索ボタンの左上隅の座標を取得
print(element.location)
※selenium version 4.1.0で動作確認をしています(ブラウザのUIや属性値などが変更された場合、実行結果が異なる可能性があります)

実行結果

#<struct Selenium::WebDriver::Point x=507.71667480468744, y=393.0>

動画デモ

※字幕を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: (403) User does not have sufficient permissions for this profile. in /home/users/1/monda-muki/web/seleniumqref.com/google-api-php-client-1-master/src/Google/Http/REST.php:110 Stack trace: #0 /home/users/1/monda-muki/web/seleniumqref.com/google-api-php-client-1-master/src/Google/Http/REST.php(62): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request), Object(Google_Client)) #1 /home/users/1/monda-muki/web/seleniumqref.com/google-api-php-client-1-master/src/Google/Task/Runner.php(174): Google_Http_REST::doExecute(Object(Google_Client), Object(Google_Http_Request)) #2 /home/users/1/monda-muki/web/seleniumqref.com/google-api-php-client-1-master/src/Google/Http/REST.php(46): Google_Task_Runner->run() #3 /home/users/1/monda-muki/web/seleniumqref in /home/users/1/monda-muki/web/seleniumqref.com/google-api-php-client-1-master/src/Google/Http/REST.php on line 110