1. 程式人生 > 實用技巧 ># 2020-10-05 #「Front End」- 使用 XPath 選擇元素

# 2020-10-05 #「Front End」- 使用 XPath 選擇元素

XPath,是在 XSLT 標準中的主要元素,用於在 XML 文件中選擇元素,我們可以理解為元素選擇器(功能上與 CSS Selectors 類似)。

我們感覺 XPath 比 CSS Selector 好用,也可能是我們不熟悉 CSS 選擇器,也可能是我們的場景使然。

學習路線(Learning Roadmap)

按照 w3school.com 章節順序進行學習即可:
1)形成 XPath 基本認識:XPath Tutorial
2)理解基本概念,比如 Parent、Children、Ancestors 等等:XPath Nodes
3)學習 XPath 語法:XPath Syntax
4)相對於當前節點定位其他節點:

XPath Axes
5)使用操作符進行判斷:XPath Operators
6)學習示例:XPath Examples

除錯 XPath 查詢(驗證 XPath 查詢是否正確)

方法一、通過瀏覽器直接獲取

我們可以使用 Chrome / Firefox 快速獲取元素的 XPath 地址。下面是 Chrome 的方法:

Inspect => Right click on the node => Copy => Copy XPath

方法二、使用 Console 除錯

在 Chrome / Firefox 的 Console 中,使用 $x('your-xpath-query')

函式,

比如:通過 $x("//img") 選擇所有圖片

常用 XPath 查詢整理(在我們工作中比較常用)

獲取在兄弟元素中的元素

html - XPath:: Get following Sibling - Stack Overflow

獲取在 div 的後續所有兄弟(sibling)元素中的 input 元素:

//div/following-sibling::input

獲取某個元素的父級元素

XPath Axes

獲取 <input id="commitBtn" /> 的父級元素:

//parent::input[@id='commitBtn']

根據屬性值的內容定位屬性

XPath with regex match on an attribute value - Stack Overflow
How to use not contains() in xpath? - Stack Overflow

定位 href 屬性包含 doubles 字串的 a 標籤:

//a[contains(@href, ' doubles ')]

定位 href 屬性不包含 doubles 字串的 a 標籤:

//a[not(contains(@href, ' doubles '))]

根據元素的位置進行定位

xml - Get Nth child of a node using xpath - Stack Overflow
xpath - XSLT getting last element - Stack Overflow

定位在 ul 中的 前三個 li 元素:

//ul[@id='thread_list']/li[position()<=3]

在所有匹配元素中,獲取最後一個元素:

(//element[@name='D'])[last()]

定位包含某個屬性的元素

xml - XPath: How to check if an attribute exists? - Stack Overflow

定位具有 foo 屬性的 span 標籤:

//span[@foo]

定位包含某種元素的元素

html - Selenium - XPATH - Searching for element by innerHTML - Stack Overflow
xml - Can XPath return only nodes that have a child of X? - Stack Overflow

定位所有包含 span[@class='split_line']div 元素:

//div[descendant::span[@class='split_line']]

定位子元素 span[@class='split_line']div 元素:

//div[span[@class='split_line']]

參考文獻

K4NZ / 使用 XPath 選擇元素
w3schools.com/XPath Tutorial
XPath - XML Path Language (XPath)
Scrapy/Docs » Selectors
Is there a way to get the XPath in Google Chrome? - Stack Overflow
How to validate XPath using Firefox Web Developer Plugin? - Stack Overflow