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

【Python】is_selected・・・要素が選択されているか判定する

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

要素に対して「is_selected」を実行することで要素が選択状態にあるかどうかを判定することが出来ます。

「is_selected」は選択状態/非選択状態が存在する要素(チェックボックス、ラジオボタン、セレクトボックス)に対して有効です。

下記のサンプルでは、cheked属性により選択状態にある『はい』ラジオボタンと、非選択状態にある『いいえ』ラジオボタンの選択状態を判定しています。「is_selected」実行することで、選択状態にある『はい』ラジオボタンはTrueが返され、それ以外はFalseが返されます。

説明

◆メソッド
  ・is_selected()
◆使用形態
  ・element.is_selected()
◆備考
  ・チェックボックスやラジオボタンなどに対して選択の有無を確認する為のメソッド
◆関連項目
  ・要素が表示されているか判定する
  ・要素が有効になっているか判定する

サンプル

from selenium import webdriver
from selenium.webdriver.chrome import service
from selenium.webdriver.common.by import By
 
#ChromeDriverのパスを変数に設定
CHROMEDRIVER = "D:\driver\chromedriver.exe"
#ChromeDriverのstartとstopを制御するServiceオブジェクトを介してパスを渡す
chrome_service = service.Service(executable_path=CHROMEDRIVER)
#Chromeを起動
driver = webdriver.Chrome(service=chrome_service)
#指定したURLに遷移する<図1>
driver.get("file://D:/AutoTest/isSelected.html")
#選択状態にある『はい』のラジオボタン要素を取得
elemYes = driver.find_element(By.ID, "ra01")
#選択状態にない『いいえ』のラジオボタン要素を取得
elemNo = driver.find_element(By.ID, "ra02")
#要素が選択されているかどうか判定
print(elemYes.is_selected())
print(elemNo.is_selected())
※selenium version 4.1.3で動作確認をしています(ブラウザのUIや属性値などが変更された場合、実行結果が異なる可能性があります)

実行結果

True
False
isSelected

isSelected.html<図1>

<!DOCTYPE html>
<html lang="ja">
    <head>
        <title>isSelected</title>
    </head>
    <body>
        <p>
            Seleniumで自動テストを実施したいですか? 
        </p>
        <p>
            <input type="radio" id="ra01" name="question" checked>はい<br>
            <input type="radio" id="ra02" name="question">いいえ<br>
            <input type="radio" id="ra03" name="question">どちらとも言えない
        </p>
    </body>
</html>

動画デモ

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