Slashes and Brackets in Web Scraping with Python 2026: XPath vs CSS Explained Introduction to the Scrapy Selector in Python 2026 Setting up a Selector in Python 2026: Best Practices for Web Scraping Selecting Selectors in Python 2026: Best Practices for Web Scraping Extracting Data from a SelectorList in Python 2026: Best Practices CSS Locators in Python 2026: Powerful Web Scraping Techniques Attributes in CSS Selectors for Web Scraping in Python 2026 Selectors with CSS in Python 2026: Modern Web Scraping Techniques Text Extraction in Python 2026: Modern Techniques & Best Practices Crawl in Python 2026: Building Modern Web Crawlers with Best Practices A Classy Spider in Python 2026: Building Web Crawlers with Elegance & Best Practices Nodriver Canvas Fingerprint Spoofing 2026 – Advanced Anti-Detection Techniques WebGL Fingerprint Spoofing Techniques 2026 – Advanced Python Web Scrapping Evasion AudioContext Fingerprint Spoofing Techniques 2026 – Advanced Python Web Scrapping Evasion WebGL + AudioContext Integration Spoofing Techniques 2026 – Advanced Python Web Scrapping Evasion Canvas + WebGL Integration Spoofing Techniques 2026 – Advanced Python Web Scrapping Evasion Web Scraping with Python 2026 Web Scraping with Python in 2026 – Complete Beginner to Advanced Guide Python Web Scraping Tutorial 2026 – Playwright, Scrapy & BeautifulSoup Guide Building Your First Scrapy Spider in 2026 – Modern Python Web Scrapping Guide View all in this category →

Slashes and Brackets in Web Scraping with Python 2026: XPath vs CSS Explained

Web Scraping Mar 24, 2026

Slashes and Brackets in Web Scraping with Python 2026: XPath vs CSS Explained

When learning web scraping, many beginners get confused by slashes (/, //) and brackets ([], ()) in selectors. These symbols are the core syntax of XPath and behave differently from CSS selectors. In 2026, understanding when to use slashes and brackets helps you write more powerful, precise, and maintainable scrapers.

This March 24, 2026 guide clearly explains the meaning and usage of slashes and brackets in modern Python web scraping using both XPath and CSS.

TL;DR — Key Takeaways 2026

  • / = direct child (like CSS >)
  • // = descendant anywhere in the document (very powerful)
  • [] = attribute or condition filter (like CSS attribute selectors)
  • Use ::text and ::attr(name) to extract content
  • CSS is usually cleaner and faster for simple tasks
  • XPath with slashes and brackets shines for complex relationships

1. Understanding Slashes in XPath


from scrapy.selector import Selector

# Small sample page so the selectors below can run as-is
html = """
<html><body>
  <div class="product"><h2> Laptop Pro 14 </h2><span class="price"> $1,299 </span>
    <a href="/p/python-laptop">View</a><img src="/img/laptop.jpg"></div>
  <div class="product"><h2> USB-C Hub </h2><span class="price"> $49 </span>
    <a href="/p/hub">View</a><img src="/img/hub.jpg"></div>
  <ul><li>First</li><li>Last</li></ul>
  <table><tr><td>row 1</td></tr><tr><td>row 2</td></tr></table>
  <button type="submit">Send</button>
</body></html>
"""
sel = Selector(text=html)

# /  → direct child
sel.xpath("/html/body/div")           # only immediate children

# // → descendant (any level)
sel.xpath("//div")                    # all divs anywhere in document
sel.xpath("//div[@class='product']")  # all product divs

# Common useful patterns
sel.xpath("//a[@href]")               # all links with href
print(sel.xpath("//img/@src").getall())   # all image source URLs

2. Understanding Brackets [] in XPath


# Filter by attribute
sel.xpath("//div[@class='product']")

# Filter by attribute value contains
sel.xpath("//a[contains(@href, 'python')]")

# Filter by position
sel.xpath("//li[1]")                  # first li
sel.xpath("//li[last()]")             # last li
print(sel.xpath("//tr[position() mod 2 = 0]//text()").getall())  # even rows

# Multiple conditions
sel.xpath("//button[@type='submit' and not(@disabled)]")

3. Real-World Example – Mixed CSS + XPath


from scrapy.selector import Selector

async def scrape_page(url):
    # ... fetch html ...
    sel = Selector(text=html)
    
    products = []
    for item in sel.css("div.product"):                    # CSS for main container
        product = {
            "title": item.css("h2::text").get().strip(),
            "price": item.css(".price::text").get().strip(),
            "link": item.xpath(".//a/@href").get(),        # XPath inside CSS
            "image": item.xpath(".//img/@src").get()
        }
        products.append(product)
    return products

4. XPath vs CSS – When to Use Which in 2026

Task CSS XPath (Slashes + Brackets)
Simple class or IDBestOkay
Text containsLimitedExcellent
Parent / sibling navigationDifficultExcellent
Position-based selectionGoodBest
Complex conditionsLimitedVery powerful

Reading XPath Paths Step by Step

An XPath expression is a series of steps separated by slashes. A single slash moves to direct children, a double slash searches all descendants, and square brackets filter the nodes at that step. Reading each step on its own makes even long expressions easy to understand.

Brackets can hold a position, such as [1] for the first matching child, an attribute test such as [@class='price'], or a function such as [contains(text(), 'Sale')]. Positions in XPath start at 1, not 0, which is a common source of off-by-one errors for Python programmers.

The choice between / and // also affects speed and robustness: // is flexible but may match more than you expect, while / follows an exact structure that breaks if the layout changes.

Worked Example: Same Page, Different Paths

We run several XPath expressions on one small page to see how slashes and brackets change the result.

from parsel import Selector

page = Selector(text="""
<div id="main">
  <ul><li>Laptop</li><li>Mouse</li></ul>
  <section><ul><li>Cable</li></ul></section>
</div>
""")

print(page.xpath("//div[@id='main']/ul/li/text()").getall())
print(page.xpath("//div[@id='main']//li/text()").getall())
print(page.xpath("//div[@id='main']/ul/li[1]/text()").get())
print(page.xpath("//li[contains(text(), 'a')]/text()").getall())

The single-slash path returns ['Laptop', 'Mouse'] because Cable sits deeper inside a section. The double-slash path returns all three items, [1] picks Laptop, and the contains filter keeps Laptop and Cable.

Common Mistakes

  • Using [0] for the first element; XPath counts from 1.
  • Using // everywhere and picking up nodes from unrelated parts of the page.
  • Forgetting text() or @attr and getting whole elements instead of values.
  • Writing exact class tests when the element has several classes.

Quick Summary

  • / means direct child, // means any descendant.
  • Brackets filter nodes at one step.
  • XPath positions start at 1.
  • End with text() or @attr to get values.

Conclusion — Slashes and Brackets in 2026

Understanding slashes (/, //) and brackets ([]) is essential for mastering XPath in web scraping. While CSS selectors are cleaner for most everyday tasks, XPath with slashes and brackets gives you unmatched power for complex page structures. In 2026, the best scrapers use a smart mix of both — CSS for speed and readability, XPath when precision and relationships matter.

Next steps:

  • Practice converting CSS selectors to XPath and vice versa

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices