How to use CSS Selectors in Nim ?

by scrapecrow Apr 16, 2024

To parse web scraped content in Nim using CSS selectors we recommend the CSS3Selectors library which is designed with web scraping in mind:

import std/streams
import pkg/chame/minidom
import css3selectors

let html = """
    <!DOCTYPE html>
    <html>
    <head><title>Example</title></head>
    <body>
        <p>1</p>
        <p>2</p>
        <p>3</p>
        <p>4</p>
    </body>
    </html>
    """
let document = Node(parseHtml(newStringStream(html)))
let elements = document.querySelectorAll("p:nth-child(odd)")
echo elements # @[<p>1</p>, <p>3</p>]

let htmlFragment = parseHTMLFragment("<h1 id='test'>Hello World</h1><h2>Test Test</h2>", Element())
let element = htmlFragment.querySelector("#test")
echo element # <h1 id="test">Hello World</h1>

CSS3Selectors was created to supersede nimquery which still works well for parsing HTML content in Nim if CSS3Selectors is not available:

from xmltree import `$`
from htmlparser import parseHtml
import nimquery

let html = """
<!DOCTYPE html>
<html>
  <head><title>Example</title></head>
  <body>
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p>
  </body>
</html>
"""
let xml = parseHtml(html)
let elements = xml.querySelectorAll("p:nth-child(odd)")
echo elements
# => @[<p>1</p>, <p>3</p>]

Related Articles

How to Parse XML

In this article, we'll explain about XML parsing. We'll start by defining XML files, their format and how to navigate them for data extraction.

PYTHON
CSS-SELECTORS
XPATH
DATA-PARSING
How to Parse XML

Ultimate CSS Selector Cheatsheet for HTML Parsing

Ultimate companion for HTML parsing using CSS selectors. This cheatsheet contains all syntax explanations with interactive examples.

CSS-SELECTORS
DATA-PARSING
Ultimate CSS Selector Cheatsheet for HTML Parsing

Web Scraping With Ruby

Introduction to web scraping with Ruby. How to handle http connections, parse html files for data, best practices, tips and an example project.

RUBY
HTTP
DATA-PARSING
CSS-SELECTORS
XPATH
INTRO
Web Scraping With Ruby

Web Scraping With NodeJS and Javascript

In this article we'll take a look at scraping using Javascript through NodeJS. We'll cover common web scraping libraries, frequently encountered challenges and wrap everything up by scraping etsy.com

NODEJS
HTTP
DATA-PARSING
CSS-SELECTORS
INTRO
Web Scraping With NodeJS and Javascript

Parsing HTML with CSS Selectors

Introduction to using CSS selectors to parse web-scraped content. Best practices, available tools and common challenges by interactive examples.

DATA-PARSING
CSS-SELECTORS
Parsing HTML with CSS Selectors

How to Scrape YouTube in 2025

Learn how to scrape YouTube, channel, video, and comment data using Python directly in JSON.

SCRAPEGUIDE
PYTHON
HIDDEN-API
How to Scrape YouTube in 2025