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

【Ruby】attribute・・・属性名から属性値を取得する

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

「attribute」の引数に属性名を指定することで属性名に対する属性値を取得することが出来ます。

下記のサンプルでは、まずGoogleトップページに存在する「I'm Feeling Lucky」ボタンの要素(Inputタグ)を取得しています。そして、取得した要素(Inputタグ)の属性であるvalue属性を「attribute」の引数として指定することで、value属性の属性値である「I'm Feeling Lucky」の文字列を取得しています。

checked属性やselected属性など一部属性は、属性値が"true"または"false"のbooleanになります。

説明

◆メソッド
  ・attribute(name)
◆使用形態
  ・element.attribute(name)
◆備考
  ・引数で指定した属性名が見つからない場合はエラーにならず何も
   出力されない。一方、属性値が設定されていない場合は「nil」が返される。

◆関連項目
  ・CSSプロパティ名からCSSプロパティ値を取得する
  ・要素の(X,Y)座標を取得する

サンプル

require 'selenium-webdriver'
 
# Firefoxを起動
driver = Selenium::WebDriver.for(:firefox)
#指定したURLに遷移する
driver.get('https://www.google.co.jp')
#I'm Feeling Luckyボタン要素をname属性名から取得
element = driver.find_element(:name,'btnI')
#I'm Feeling Luckyボタンのvalue属性名の属性値を取得
valString = element.attribute('value')
#取得した文字列をコンソール出力
print(valString)
※selenium version 4.1.0で動作確認をしています(ブラウザのUIや属性値などが変更された場合、実行結果が異なる可能性があります)

実行結果

I'm Feeling Lucky
getAttribute2
 ※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