0
1

More than 1 year has passed since last update.

XPath を Element から相対的に指定する

Posted at

意外と調べても見当たらなかった(調べ方が悪い?)ので、自分の覚書。
Python & Selenium ですが、他の XPath を利用する場合にも使えるんじゃないかな?

HTML 要素(最上位要素)を基準に、要素を取得する場合

XPath の情報でよく見る記載です。

よく散見される、Selenium による XPath の指定
from selenium import webdriver
from webdriver_manager.microsoft import EdgeChromiumDriverManager
(中略)
# WebVriverをwebdriver_managerで取得
driver = webdriver.Edge(EdgeChromiumDriverManager().install())
# driver = webdriver.Edge(r"C:\〇〇〇\edgedriver_win64\msedgedriver.exe")
(中略)
driver.find_element_by_xpath('//*[@id="password"]').send_keys(passw)

この '//*[@id="password"]' の表現ですが、// は、先頭に記載されることによって、HTML文書の最上位要素である<html>タグを基準にして、そこから XPath の記載に従った要素取得を行う内容となっています。

取得したエレメントの子要素を、ループで回して処理したい!

例えば、検索サイトである単語でWeb検索を行い、その中から指定のページを見つけて開く、という処理を考えた場合、検索結果全体を表示するdivエレメントを取得し、その子要素をループにかけたい場合もあると思います。

対象のページのタイトルが分かってるなら、//*[contains(text(),"タイトル文字")] で取得できる、というツッコミは無しで。
そういう類のモノではないという前提です。

for temp_element in driver.find_elements_by_xpath('//*[@id="tree-1-El"]/child::div[starts-with(@id,"tree-panel-")]'):
    temp_element_child = temp_element.find_element_by_xpath('temp_element 要素の下にある、id が "header-title-" で始まる、div 要素')
    if temp_element_child.text == 'テキスト1':
        temp_ele_text1 = temp_element
    elif temp_element_child.text == 'テキスト2':
        temp_ele_text2 = temp_element

temp_element 要素の下にある、id が "header-title-" で始まる、div 要素 を、XPath でどの様に指定すればよいか?

勿体付けずに、正解はこちら

for temp_element in driver.find_elements_by_xpath('//*[@id="tree-1-El"]/child::div[starts-with(@id,"tree-panel-")]'):
    temp_element_child = temp_element.find_element_by_xpath('.//div[starts-with(@id,"header-title-")]')
    if temp_element_child.text == 'テキスト1':
        temp_ele_text1 = temp_element
    elif temp_element_child.text == 'テキスト2':
        temp_ele_text2 = temp_element

'.//div[starts-with(@id,"header-title-")]' が該当箇所です。
単純に、.// で始まるように指定すればよかったんですね。
/ とか ./ で上手くいかずに、無駄な時間を使いました・・・

XPath は、極めるととても便利

XPath は、とても奥が深いんですよね、私は下記のサイトを参考にしています。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1