Skip to content

Getting started

Here’s the smallest useful thing Parsec does: take a page, parse it the way a browser would, and pull out the elements you want with a CSS selector. Each tab below runs as written and prints the same two lines.

Terminal window
cargo add parsec-web
use parsec::css::SelectorList;
fn main() {
let doc = parsec::parse(
r#"<ul>
<li class="book"><a href="/p/1">Dune</a></li>
<li class="book sold"><a href="/p/2">Emma</a></li>
<li class="book"><a href="/p/3">Ulysses</a></li>
</ul>"#,
false,
);
let in_stock = SelectorList::parse("li.book:not(.sold) a").unwrap();
for a in in_stock.select(&doc, doc.root()) {
let href = doc.attrs(a).find(|&(_, name, _)| name == "href").map(|(_, _, value)| value);
println!("{} {}", doc.text(a), href.unwrap_or(""));
}
}

The package is parsec-web, and the library inside it is parsec, so your code says use parsec::…. The false is for scripting: pass true only if you want <noscript> read the way a browser with JavaScript on reads it.

All three print:

Dune /p/1
Ulysses /p/3

Notice what you didn’t have to write. There’s no <html>, <head> or <body> in that markup, and it doesn’t matter: Parsec adds them where the HTML Standard says they go, the same as a browser. It never fails on bad markup, because the standard says how to recover from every mistake, and Parsec follows it.

From C, the library is a header and a static or shared library for each platform; install says where to get them.