トップページ > Selenium API(逆引き) > 【Python】find_element(By.XPATH, "xxx")

【Python】find_element(By.XPATH, "xxx")・・・xpathから要素を取得する

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

「find_element(By.XPATH, "xxx")」の"xxx"にxpathを指定することで要素を取得することが出来ます。

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

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

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

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

説明

◆メソッド
  ・find_element(By.XPATH, xpath)
◆使用形態
  ・driver.find_element(By.XPATH, "//div/div/td[1]")
◆備考
  ・引数に取得したい要素のxpathを指定することで要素を取得できる
  ・引数で指定する属性値やインナーテキストなどの「値」はシングルクォーテーションで囲われる必要がある
◆関連項目
  ・id属性から要素を取得する
  ・name属性から要素を取得する

サンプル

from selenium import webdriver
from selenium.webdriver.chrome import service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

#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に遷移する
driver.get("https://www.google.co.jp")
#Googleの検索テキストボックスの要素をxpathから取得
element = driver.find_element(By.XPATH, "//*[@id='lst-ib']")
#検索テキストボックスに"xpathとは?"を入力
element.send_keys("xpathとは?")
#Enterキーを押下してGoogle検索を実行
element.send_keys(Keys.ENTER)
※selenium version 4.1.3で動作確認をしています(ブラウザのUIや属性値などが変更された場合、実行結果が異なる可能性があります)

実行結果

xpath
 ※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