LoginSignup
13

More than 3 years have passed since last update.

よく使うXpath

Last updated at Posted at 2017-10-20
1 / 17

私が最近よく使うXpathについて話す。
Xpathを理解するとプログラミング言語並みに色々できることがわかったので知見を共有します。
サンプルのXpathのデモに使うページはここ


集合操作・検索


()

xpathの結果をそのまま変数として扱う

//a[text() = (//*[@id="service-index"]/div[4]/div/div/div/div[2]/div[1]/a/text())]/text()

contains(arg1, arg2)

arg2の文字列を含むarg1の集合を返す

//*[contains(@class, 'is-text')]

following-sibiling::

現ノードに対し兄弟関係にあるノードの弟を返す

//*[@id="news-index"]/div[1]/div[1]/ul/li[2]/a/span/i/following-sibling::node()

position()

現ノードの集合における、親ノードからみた順番で範囲選択する

(//*[@id="news_all"]//div[contains(@class, 'title')]/a)[position() >= 2]

文字列操作


concat(arg1, arg2, ..., argn, ...)

引数の文字列を連結する

concat(//*[@class = 'nav-item'][1]/text(), //*[@class = 'nav-item'][2]/text())

normalize-space(arg)

文字列引数の前後に含まれる空白文字をトリムする

normalize-space(concat(//*[@class = 'nav-item'][1]/text(), //*[@class = 'nav-item'][2]/text()))

translate(arg1, arg2, arg3)

arg2に渡された文字をarg3に変換されたarg1を返す

translate(normalize-space((//*[@id="news_all"]//div[contains(@class, 'title')]/a)[position() = 1]), 'CTO', 'CEO')

substring-before(arg1, arg2) substring-after(arg1, arg2)

arg2で分割された前後のarg1を返す

substring-before(normalize-space((//*[@id="news_all"]//div[contains(@class, 'title')]/a)[position() = 2]), '、')
substring-after(normalize-space((//*[@id="news_all"]//div[contains(@class, 'title')]/a)[position() = 2]), '、')

論理演算


and

論理積の条件にあったノードの集合を返す

//*[@class = 'nav-item' and contains(text(), 'ニュース')]

or

論理和の条件にあったノードの集合を返す

//*[contains(@class, 'is-text') or contains(@class, 'nav-item')]

not()

条件式の否定に沿ったノードの集合を返す

//*[@class = 'nav-item' and not(contains(text(), 'ニュース'))]

appendix

ここ見れば大体載ってる

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
13