LoginSignup
36
46

More than 5 years have passed since last update.

XPathで指定したテキストがある次の要素を取得する方法

Posted at

(備忘録です)

本文

XPathはHTMLなどで使えるノードを抜き出せる言語です。

PHPやPythonなどいろんな言語で利用できます。
XPathの構文などはチートシートなどを参照してください。

あと便利機能ですが、Google ChromeDeveloper ToolsでCtrl+Fなどで呼び出せる検索(Find)ボックスにXPathを入力し対象ノードを検索することが出来ます。

では、
http://qiita.com/about

このページから以下の図のような
「細かい検索オプション」の次のPタグを抜き出したいと思います。

スクリーンショット 2015-03-10 22.34.47.png

では、おもむろに、以下の図のように
Google ChromeDeveloper Toolsの「細かい検索オプション」のノードを右クリックし、「Copy XPath」をクリックします。

スクリーンショット 2015-03-10 21.46.27.png

すると、以下の様なXPathをクリップボードにコピーできます。

XPath-細かいオプション
//*[@id="main"]/div/div/div/div/h3[2]

もちろんこのまま検索ボックスに入力すると対象ノードを検索できます。

すこしこれを弄って、
/following::p を追加すると 前半の対象ノードの結果を用いた検索ができます。

(h3[2]の代わりにtext()=などにしてなんとなく汎用性)

XPath-「細かいオプション」の次のPタグ
//*[@id="main"]/div/div/div/div/*[text()="細かい検索オプション"]/following-sibling::p

following-siblingの代わりにParent等色々できます。

DOM構造も任意にするとこんな感じですかね。

XPath-「細かいオプション」の次のPタグ-2
//*[text()="細かい検索オプション"]/following-sibling::p

参考

XPath チートシート
http://aoproj.web.fc2.com/xpath/XPath_cheatsheets_v2.pdf

XPath
http://itref.fc2web.com/xml/xpath.html

36
46
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
36
46