0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【保存版】XPathの使い方まとめ|実用的なサンプルコード大全

Last updated at Posted at 2018-05-24

XPath(XML Path Language)は、HTMLやXML文書から要素を抽出するためのパス式です。Seleniumやスクレイピングで広く使われており、正確な要素取得に不可欠です。

この記事では、実用的なXPath構文を豊富なサンプル付きでまとめました。


🔰 基本構文と記法

XPathは、パス表現によりノード(要素や属性など)を指定します。

//tagname[@attribute='value']

例://div[@class='item']


🧱 ノードの指定と階層移動

構文 説明
/ ルートからの絶対パス /html/body/div
// 文書内のどこかにある任意の位置から //a(すべてのリンク)
. カレントノード ./div
.. 親ノード ../div
@ 属性指定 //@href(すべてのリンク先)

🧩 属性を使った指定

//input[@type='text']        type属性がtextinput
//div[@id='main']            idmaindiv
//a[@href='/login']          href/loginのリンク

属性が複数マッチ:

//button[@class='btn' and @type='submit']

🔎 テキストに基づく抽出

完全一致

//p[text()='こんにちは']

部分一致(contains()

//p[contains(text(), 'こんにちは')]

前方一致(starts-with()

//span[starts-with(text(), 'エラー')]

🪄 属性値の部分一致

//div[contains(@class, 'header')]

これは class="site-header header-main" など複数クラスを持つ要素にも対応可能。


🔢 インデックス指定(リスト対応)

最初の要素

(//li)[1]

最後の要素

(//li)[last()]

n番目の要素

(//ul[@class='items']/li)[3]

🧠 条件付き抽出(論理演算)

//input[@type='checkbox' and @checked]
//div[@class='notice' or @class='alert']

🌳 子要素/親要素/兄弟要素

子要素

//div[@id='main']/p          id="main" の子p

親要素

//p[@class='desc']/..        class="desc" pの親要素

兄弟要素

//h2[text()='セクション']/following-sibling::ul

📋 ノードの種類指定

ノード種別 XPath
すべての要素 //*
属性 //@*
コメント //comment()
テキストノード //text()
処理命令ノード //processing-instruction()

💡 応用:HTMLスクレイピングでの使用例(Python + lxml)

from lxml import html
tree = html.fromstring(html_string)

# aタグのhrefをすべて取得
hrefs = tree.xpath('//a/@href')

# classに「item」を含むdivのテキストを取得
items = tree.xpath("//div[contains(@class, 'item')]/text()")

🧪 応用:SeleniumでのXPath指定

from selenium import webdriver

driver = webdriver.Chrome()

# XPathで要素取得
element = driver.find_element("xpath", "//input[@name='q']")

# 部分一致でボタン取得してクリック
button = driver.find_element("xpath", "//button[contains(text(), '検索')]")
button.click()

📌 よく使うXPathパターンまとめ

目的 XPath例
特定のテキストを含む要素 //tag[contains(text(), '文字列')]
クラス名が含まれる要素 //div[contains(@class, 'target')]
特定属性を持つタグ //img[@alt='logo']
要素リストの最初・最後 (//li)[1], (//li)[last()]
子/親/兄弟要素の取得 /, .., following-sibling::

📝 まとめ

  • XPathは構文が多彩ですが、最小限覚えると強力な武器になります。
  • 特に //, @, contains(), text()、そしてインデックス指定は実務でよく使います。
  • SeleniumやBeautifulSoupと組み合わせて、HTMLの要素取得を精密に制御できます。
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?