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

【Ruby】find_element(:css, 'xxx')・・・cssセレクタから要素を取得する

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

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

cssはスタイルシートと呼ばれ、Webページに対してレイアウトやデザインを施す為の言語を表します。また、cssセレクタはcssのレイアウトを施す場所(対象)を意味しcssセレクタには、タグ名,id属性,class属性などを指定していきます。

下記サンプルでは、検索テキストボックスの要素を取得する為、クラス属性である「.gsfi」を「find_element(:css, 'xxx')」の'xxx'に指定していることが分かります。

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

説明

◆メソッド
  ・find_element(:css, 'xxx')
◆使用形態
  ・driver.find_element(:css, 'xxx')
◆備考
  ・第二引数に取得したい要素のCSSセレクタを指定することで、要素を取得できる
◆関連項目
  ・id属性から要素を取得する
  ・linkTextから要素を取得する

サンプル

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

実行結果

cssSelector3
cssSelector4
 ※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