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

【Ruby】find_element(:xpath, "xxx")・・・xpathから要素を取得する

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

「find_element(:xpath, "xxx")」の第二引数である"xxx"にxpathを指定することで要素を取得することが出来ます。

xpathとは、XML Pathを省略したものです。xpathは構文が定められており、その構文に従ったxpathを「find_element(:xpath, "xxx")」の"xxx"に指定する必要があります。

ただ、構文に従って記入するというよりも、Chromeデベロッパー・ツール(Chromeを立ち上げて「F12」キーを押下)やFireBugの拡張機能であるFirePathを用いることで、ターゲットのxpathを手軽に調べることが出来ます。

xpathは一意に要素を取得することができる便利な記法ですが、UIが変更された場合、ページ内の全ての要素が影響を受ける(xpathが変わってしまう)可能性があるので注意が必要となります。

※要素取得の詳細についてはこちら

説明

◆メソッド
  ・find_element(:xpath, "xxx")
◆使用形態
  ・driver.find_element(:xpath, "//*[@id='lst-ib']")
◆備考
  ・第二引数に取得したい要素のxpathを指定することで要素を取得できる
  ・第二引数で指定する属性値やインナーテキストなどの「値」はシングルクォーテーションで囲われる必要がある
◆関連項目
  ・アクティブな要素を取得する
  ・class属性から要素を取得する

サンプル

require 'selenium-webdriver'
 
# Firefoxを起動
driver = Selenium::WebDriver.for(:firefox)
#指定したURLに遷移する
driver.get('https://www.google.co.jp')
#Googleの検索テキストボックスの要素をxpathから取得
element = driver.find_element(:xpath,"//*[@id='lst-ib']")
#検索テキストボックスに"xpathとは?"を入力し検索を実行
element.send_keys('xpathとは?', :enter)
※selenium version 4.1.0で動作確認をしています(ブラウザのUIや属性値などが変更された場合、実行結果が異なる可能性があります)

実行結果

xpath2
 ※GoogleおよびGoogleロゴはGoogle Inc.の登録商標であり、同社の許可を得て使用しています。

動画デモ

※字幕を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