# curl https://devtools.krishanchawla.com/raw/complete-xpath-cheatsheet.txt COMPLETE XPATH CHEATSHEET Complete generic XPath reference with real-world patterns and examples for locating elements in HTML and XML Category: Web · Type: cheatsheet Official docs: https://www.w3.org/TR/xpath/ ──────────────────────────────────────────────────────────── ## What is XPath? **XPath (XML Path Language)** is a query language used to locate and navigate elements within HTML and XML documents. It allows precise element selection using tags, attributes, text, and DOM relationships. **⚡ Key Features** - DOM traversal - Attribute and text matching - Axis-based navigation - Tool and language agnostic **🎯 Use Cases** - UI automation - Web scraping - DOM inspection - Dynamic element identification --- ## 📍 XPath - Absolute Path Select element using full DOM hierarchy. XPath: ```plaintext /html/body/div/form/input ``` Example (HTML): ```html
``` Avoid in real projects due to fragility. ## 🎯 XPath - Relative Path Select element anywhere in the document. XPath: ```plaintext //input ``` Example (HTML): ```html ``` Recommended for maintainable locators. ## 🏷️ XPath - Select by Tag Name Select elements by HTML tag. XPath: ```plaintext //button ``` Example (HTML): ```html ``` ## 🔍 XPath - Select by Attribute Match exact attribute value. XPath: ```plaintext //input[@id='username'] ``` Example (HTML): ```html ``` ## 🔗 XPath - Multiple Attributes Match multiple attribute conditions. XPath: ```plaintext //input[@type='text' and @name='email'] ``` Example (HTML): ```html ``` ## 🔀 XPath - OR Condition Match any one condition. XPath: ```plaintext //input[@id='email' or @name='email'] ``` Example (HTML): ```html ``` ## 📌 XPath - contains() Attribute Partial attribute match. XPath: ```plaintext //div[contains(@class,'header')] ``` Example (HTML): ```html ``` ## ▶️ XPath - starts-with() Match attribute prefix. XPath: ```plaintext //input[starts-with(@id,'user_')] ``` Example (HTML): ```html ``` ## ✏️ XPath - Exact Text Match Match exact visible text. XPath: ```plaintext //button[text()='Login'] ``` Example (HTML): ```html ``` ## 📝 XPath - contains(text()) Match partial visible text. XPath: ```plaintext //span[contains(text(),'Welcome')] ``` Example (HTML): ```html Welcome John ``` ## 🧹 XPath - normalize-space() Ignore extra whitespace. XPath: ```plaintext //button[normalize-space()='Submit'] ``` Example (HTML): ```html ``` ## 🔢 XPath - Index Selection Select element by position (1-based). XPath: ```plaintext (//input[@type='text'])[1] ``` Example (HTML): ```html ``` Use cautiously — indexes may change. ## 🔚 XPath - last() Function Select last matching element. XPath: ```plaintext (//button)[last()] ``` Example (HTML): ```html ``` ## ⬆️ XPath - Parent Axis Navigate to parent element. XPath: ```plaintext //input[@id='email']/parent::div ``` Example (HTML): ```html