XPath selects nodes in an HTML document tree. In Scrapy, write the expression with response.xpath(), then call .get() for one value or .getall() for every match. The most important rules are scope (// versus .//), predicate position (//li[1] versus (//li)[1]), and the difference between text nodes, attributes and an element’s complete string value.
XPath in one minute
The W3C XPath 1.0 Recommendation defines XPath as “a language for addressing parts of an XML document, designed to be used by both XSLT and XPointer” (16 November 1999). HTML scrapers use the same tree-addressing idea after a parser turns the response into elements, text nodes and attributes.
Scrapy’s selector API is a thin wrapper around Parsel, which uses lxml underneath. A Scrapy response can therefore expose both XPath and CSS selection:
title = response.xpath("//title/text()").get()
links = response.xpath("//a/@href").getall()
.get() returns the first selected result, or None when there is no match (you can provide a default). .getall() always returns a list, including an empty list when nothing matches.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Core XPath cheatsheet
| Goal | XPath | Result and use |
|---|---|---|
| Select every heading | //h1 |
All matching h1 elements. |
| Get heading text nodes | //h1/text() |
Direct text-node children only; nested text needs a descendant query. |
| Read links | //a/@href |
The href attribute from every anchor. |
| Filter an attribute | //a[contains(@href, "image")]/@href |
Anchors whose URL contains the chosen substring. |
| Find an ID | //div[@id="images"] |
Elements with that exact id. |
| First title value | //title/text() |
Use .get() to return one string. |
| All image URLs | //img/@src |
Use .getall() for a list. |
| Descendants of a selected container | .//p |
Paragraphs below the current selector, not elsewhere in the document. |
Understand scope: //, .// and child paths
Document-wide searches
// starts a search from the document root. In a loop over product cards, this is a common mistake:
for card in response.xpath("//article[contains(@class, 'product')]"):
name = card.xpath("//h2/text()").get()
The inner //h2 can select headings from the entire document, so every card may receive the same first heading. Use a relative descendant path instead:
for card in response.xpath("//article[contains(@class, 'product')]"):
name = card.xpath(".//h2/text()").get()
Relative descendants and direct children
.//p means any paragraph beneath the current node. A bare p selects only direct child paragraphs. Choose the latter when nested cards or footer content must not be included.
Predicates and positional traps
Why //li[1] can return several nodes
Predicates are evaluated in each relevant parent context. //li[1] means the first li child under each parent, so a document with several lists can produce several results. To select the first list item in document order, group the complete result first:
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteRank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
first_item = response.xpath("(//li)[1]").get()
Likewise, //div[@class="card"]//a[1] selects the first matching anchor in each card context, while (//div[@class="card"]//a)[1] selects one anchor globally.
Useful predicate forms
//button[@disabled]selects elements that have adisabledattribute, regardless of its value.//input[@type="email"]tests an exact attribute value.//p[position() > 1]skips the first paragraph in each context.//li[last()]gets the last item in each relevant list.//a[contains(., "Next")]/@hreftests the element’s combined text, including nested markup.
Text extraction: nodes versus element values
Direct text and nested text
//h1/text() returns direct text-node children. If markup splits the visible text, such as <h1>Price <em>today</em></h1>, the nested word is not included by that expression. Use .//text() for every descendant text node:
parts = response.xpath("//h1//text()").getall()
heading = " ".join(part.strip() for part in parts if part.strip())
Use . for a combined string test
When a string function receives a node-set such as .//text(), XPath 1.0 converts only the first node for that function. Thus contains(.//text(), "Next Page") can fail when “Next Page” is split by a nested element. contains(., "Next Page") checks the element’s string value, including descendant text:
next_url = response.xpath("//a[contains(., 'Next Page')]/@href").get()
Use .//text() when you need individual text pieces; use . when testing or extracting the element’s combined textual value.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Classes, IDs and robust matching
Why exact class equality is fragile
Class attributes are space-separated token lists. @class="price" misses class="price sale". A raw contains(@class, "price") can incorrectly match a token such as price-large. Use a token-safe expression:
price_nodes = response.xpath(
"//*[contains(concat(' ', normalize-space(@class), ' '), ' price ')]"
)
For ordinary class-based selection, CSS is often clearer, then XPath can handle text, attributes or relationships:
cards = response.css("article.product")
for card in cards:
sku = card.xpath("./@data-sku").get()
IDs are usually more stable when the page provides them: //div[@id="images"]. Still inspect the response rather than assuming an ID is unique or permanent.
Relationships that make XPath expressive
- Parent:
//span[@class="label"]/..selects the immediate parent. - Ancestor:
//input[@name="q"]/ancestor::form[1]finds the nearest form. - Following sibling:
//h2[normalize-space()="Specs"]/following-sibling::ul[1]. - Descendant:
//section[@id="content"]//imgfinds images at any depth. - Attribute wildcard:
//div[@*[starts-with(name(), "data-")]]finds elements having adata-attribute.
Prefer a stable anchor (ID, data attribute or meaningful relationship) over a long chain of positional steps that breaks when the layout changes.
Recommended Free Tools
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Scrapy extraction patterns that avoid silent errors
One value with a fallback
title = response.xpath("normalize-space(//title)").get(default="Untitled")
Scrapy’s selector result still needs .get(). For a cleaner text value from an element:
summary = response.xpath("normalize-space(string(//meta[@name='description']/@content))").get(default="")
Many values and aligned fields
for row in response.xpath("//table[@id='orders']//tr[position() > 1]"):
yield {
"order": row.xpath("normalize-space(./td[1])").get(),
"status": row.xpath("normalize-space(./td[2])").get(),
}
Scope each field to row with ./ or .//; otherwise a document-wide expression can mix data from unrelated rows.
Namespaces, parsers and dynamic pages
Namespaces in XML and feeds
A namespace-free query such as //link may return nothing in a namespaced XML feed. Bind the namespace prefix in the selector API and use that prefix in XPath, or deliberately call Scrapy’s remove_namespaces(). Removing namespaces changes the tree and has a processing cost, so use it only when that trade-off is acceptable.
Choose the response and parser deliberately
XPath syntax is separate from parser behavior. HTML and XML response types can produce different trees, especially around malformed markup. Inspect the actual response body and parsed structure, and use the response type appropriate for the content.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
JavaScript-rendered content
XPath can only select nodes present in the parsed response. If a browser creates products after JavaScript runs, the initial Scrapy response will not contain them. Render the page with a suitable browser workflow, then apply XPath to the rendered HTML; changing the expression alone cannot create missing nodes.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.XPath versus CSS in Scrapy
| Need | Usually clearer choice | Reason |
|---|---|---|
| Classes and straightforward structure | CSS | Short, readable selectors; Scrapy translates CSS queries into XPath internally. |
| Text nodes or attributes | XPath | Explicit text(), attribute axes and string functions. |
| Parent, sibling or conditional relationships | XPath | Axes and predicates express relationships directly. |
| Simple descendant selection inside a known container | Either | Choose the style your team can maintain. |
Parsel can be used without Scrapy and relies on lxml. lxml parses HTML and XML but is not included in Python’s standard library.
Troubleshooting checklist
No results
- Print or save the response body and verify the target node exists in the received HTML.
- Check whether the page is JavaScript-rendered and whether the response type handles the markup as expected.
- For XML, check namespaces; bind a prefix or intentionally remove namespaces.
- Confirm attribute spelling, quoting and case.
Too many results
- Replace document-wide
//inside a container loop with.//. - Use parentheses when you mean the first result globally:
(//li)[1]. - Use
.get()only when one value is expected; validate cardinality with.getall()during development.
Wrong or incomplete text
- Replace
text()with.//text()when nested elements split the text. - Use
contains(., "term"), notcontains(.//text(), "term"), for a combined-text condition. - Normalize whitespace with
normalize-space()before storing labels.
Class selector misses cards
Account for multiple class tokens with the token-safe expression, or select the class using CSS and chain a relative XPath.
Or skip the browser setup
When your goal is a clean screenshot of the page you are parsing or documenting, ScreenshotNeo provides a website screenshot API and MCP server. It accepts consent banners like a visitor, removes more than 60 known consent platforms plus newsletter popups and chat widgets, and lets you turn each cleanup step off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed; response headers identify the page verdict and whether it was billed.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsOne request is enough:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python:
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
See the ScreenshotNeo documentation for all 63 options, including full-page and element captures, device and retina settings, PDFs, custom CSS and JavaScript, clicks, waits, blocking, headers, cookies, geolocation, caching, signed links, asynchronous jobs, bulk capture and usage reporting. Its MCP tools—take_screenshot, get_page_info and capture_pdf—work with Claude, Cursor and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Practical design rules
- Start with the smallest stable anchor, then add predicates.
- Decide whether the result should be one node or a list before choosing
.get()or.getall(). - Make scope explicit with
./and.//inside loops. - Test against missing, repeated and nested markup, not only the happy-path page.
- Keep parser, namespace and rendering decisions separate from XPath syntax so failures are diagnosable.
Frequently Asked Questions
Can XPath select an HTML attribute directly?
Yes. Use the attribute axis shorthand, such as //a/@href or //img/@src, then call .get() or .getall().
How do I know whether a selector is relative?
A selector beginning with .// or ./ is relative to the current selected node. A selector beginning with // searches from the document context.
Does XPath execute JavaScript?
No. It queries the parsed tree it receives. Render dynamic content first if the target nodes are created by JavaScript.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

