Slicing HTML with CSS selectors

This code extracts HTML that matches CSS3-ish selectors.

I won't say I outright stole Mark Pilgrim's HTML parser code, but how many ways are there to use sgmllib? I certainly used his code as a model though.

It doesn't support combinators (foo + bar, foo > bar, foo ~ bar), though it does descendence (foo bar) just fine. Actually it'll parse the combinators, it just won't denote them in any way; the HTML parser will ignore them.

It doesn't do pseudos (e.g., :first-child) either. That was too much engineering up front to accomplish in one thunk, and, well... this is already a step up from the application it's replacing.

The attribute comparators it supports are:

=
Attribute must exactly equal the value.
~=
Attribute must contain the value in a space-separated list (e.g., class attributes).
|=
Attribute must contain the value in a hyphen-separated list (i.e., lang attributes).
^=
Attribute must begin with the value.
$=
Attribute must end with the value.
*=
Attribute must contain, somewhere, the value.

For example, selector img[src*="foo"] will match all img tags with the text "foo" in their src URLs.

Yes, this is for Stapler.py. Thanks for asking.

TrackBack

Listed below are links to weblogs that reference Slicing HTML with CSS selectors:

» Oops CSS HTML from markpasc.org
Yes, I forgot to upload the files for the previous entry. No, they're no longer missing. [Read More]

» Stapler.py 0.9 from markpasc.org
Wow, it runs. Yay. [Read More]

Profile

Hi, I'm Mark and this is my web site.

I work at Six Apart on TypePad.

Wii T-shirt

exploded wiimote. awesome.

A “Yakuza War” has started in Central Tokyo - Japan: Stippy

"This has lit a match of dangerous and lethal proportions, escalating a rift that has been brewing in Tokyo for some time now, starting the much feared 'Yakuza war' in central Tokyo, that many have been predicting since the end of 2005."

FLCL: Vol. 3

This disc includes the following episodes: "Bura-Bure" and "Furi Kura." Extras include director's commentary, outtakes and an art gallery. Shipped on 02/05/07.

Seven Days in May

Military aide Kirk Douglas stumbles across a plot by his boss (Burt Lancaster) to overthrow the U.S. president (Fredric March), who has just negotiated a controversial peace treaty. Douglas' dilemma: Follow orders and remain silent, or betray his boss. Director John Frankenheimer demonstrates the same mastery that made The Manchurian Candidate a classic, and Lancaster gives an effective performance in an unsympathetic role. Shipped on 02/05/07.

Obsessed by personalities, they've forgotten what democracy is for | Special reports | Guardian Unlimited

"And so in the Washington Hilton the permanent campaign that transforms American politics into a never-ending soap opera continues."

Chesnut Hill George iPod Sound System With Funky Remote - Gizmodo

Comment on smoke test

Spooky.

smoke test

Clusty Search (optimized for wii)

Boing Boing Boing 009 2006-01-16 on Odeo

Ajaxian » Joe Hewitt Firebug power user demo

Gamasutra - Feature - Gamasutra Podcast Transcript - An Interview With Susan O'Connor

via ars technica's opposable thumbs

EyeMelt.com

online comic book distribution

Gamasutra.com - Statistically Speaking, It's Probably a Good Game, Part 2: Statistics for Game Designers

OpenID Enabled: OpenID Tests

This says Technorati doesn't support checkid_immediate in dumb mode, which is what my plugin uses, yeah

FLCL: Vol. 2

This disc includes the following episodes: "Maru-Raba" and "Furi Kiri." Extras include director's commentary, outtakes and an art gallery. Shipped on 01/30/07.

Joel Spolsky in Founders At Work

every Joel on Software article ever, hypercondensed into an interview

Me and You and Everyone We Know

Today's world of technology and convenience makes it increasingly difficult to find a real connection with another person. In this compelling look at the everyday human experience, Christine (Miranda July) is a cab driver and artist who leads a solitary life. Richard (John Hawkes) is a recently divorced father who's waiting for great things to happen in his life. When his path crosses with Christine's, he's both entranced and panic-stricken. Shipped on 01/30/07.

SECOND LIFE: Put your money on World of Warcraft - Valleywag

"[T]he 3D worlds program in the next decade is likely to resemble the AI program in the last century, where early optimism about rapid progress on general frameworks gave way to disconnected research topics (machine vision, natural language processing) and 'toy worlds' environments."

10 Free Apps Every Mac User Should Have - JakeJarvis.com

Lingr: Chatrooms for the people

Web 2.0 reinvents IRC

Unhappy Meals - Michael Pollan - New York Times

The story of how basic questions about what to eat got so complicated reveals a great deal about the institutional imperatives of the food industry, nutritional science and journalism.

Snipshot: Edit pictures online

online image editor -- with api!

Ned Batchelder: How to make business card cubes

Feature Highlights // Mint

Nice improvements and shiny new look, but worth $19? Not yet convinced

jTunes: The insanely great songs Apple won't let you hear - By Paul Collins - Slate Magazine

"'Killer Tune' is just that: It sounds like the Killers, and it is killer. It's one of the most popular iTunes downloads for the band Straightener—but you haven't heard it. You *can't* hear it." via Ars Technica's Infinite Loop

The Trouble with Tom: The Strange Afterlife and Times of Thomas Paine by Paul Collins

Don Park's Daily Habit - Identicon: Updated and Source Released

Wordplay

From the masters who create the mind-bending diversions to the tense competition at the American Crossword Puzzle Tournament, Patrick Creadon's documentary reveals a fascinating look at the addictive pastime. Creadon captures New York Times editor Will Shortz working with crossword puzzle builders, talks to celebrity solvers -- including Bill Clinton and Ken Burns -- and presents an intimate look at the national tournament and its competitors. Shipped on 01/23/07.

In the Realms of the Unreal

By day, Henry Darger was a reclusive janitor who had few -- if any -- friends. But at night, he became a literary artist with a unique vision. Darger's 15,000-page novel is a wonderland of imagination as it details the exploits of seven angelic sisters who lead a rebellion against child-enslaving men. Featuring the voices of Dakota Fanning and Larry Pine and the work of talented animators, this film tells the story of Darger's hidden world. Shipped on 01/23/07.

Dead Man

Only Jim Jarmusch could direct a Western like this: A poetry-loving American Indian mistakes accountant William Blake (Johnny Depp) for the English writer of the same name, while bounty hunters take Depp for a murderer. Jarmusch packs the film with an unlikely collection of castmates, including Iggy Pop, Gabriel Byrne, John Hurt, and Robert Mitchum in one of his last roles. Shipped on 01/23/07.

Riverfold Software - Wii Transfer

Twitch - Production I.G. enters live-action 'Ghost in the Shell' forray

If we're lucky it might be as good as the live action Aeon Flux movie

Who Killed the Electric Car?

Amid ever-increasing gas prices, this documentary delves into the short life of the GM EV1 electric car -- once all the rage in the mid-1990s and now fallen by the roadside. How could such an efficient, green-friendly vehicle fail to transform our garages and skies? Through interviews with government officials, former GM employees and concerned celebs (such as EV1 driver Mel Gibson), Chris Paine (former EV1 owner) seeks to answer the question. Shipped on 01/19/07.

Amazon.com: Black Leather Zipper Case fits Apple iPhone by Incipio - Black: Electronics

the next missing bullet is "* Apple iPhone!!!"

FLCL: Vol. 1

This disc includes the following episodes: "Fooly Cooly," and "Fire Starter." Extras include director's commentary, outtakes and an art gallery. Shipped on 01/16/07.

The Work of Director Anton Corbijn

Dutch artist Anton Corbijn is known as much for the music videos he directs as his famous photographs. This collection gathers his best work in the former medium, including Propaganda's "Dr. Mabuse," Joy Division's "Atmosphere," Joni Mitchell and Peter Gabriel's "My Secret Place" and Depeche Mode's "It's No Good." Also featured are promotional trailers aired on MTV with Beck and Dave Grohl, interviews with Samantha Morton and U2 and more. Shipped on 01/16/07.

The Matrix

In this complex story that aspires to mythology, a computer hacker (Keanu Reeves) searches for the truth behind the mysterious force known as the Matrix. He finds his answer with a group of strangers led by the charismatic Morpheus (Laurence Fishburne). What they encounter in confronting that truth makes for a lightning-paced, eye-popping thrill ride of a movie that cleverly combines sociopolitical commentary with cutting-edge special effects. Shipped on 01/16/07.

The King

After serving time in the Navy, 21-year-old Elvis (Gael Garcia Bernal) decides to look up the father (William Hurt) who abandoned him as a child, only to find him working as a small-town pastor with a new wife (Laura Harring) and two teenage children (Pell James and Paul Dano). While his father is unwilling to disrupt his life to reconcile with his son, Elvis refuses to be ignored, taking drastic measures to insert himself into the family. Shipped on 01/11/07.

Mystery Science Theater 3000: Timechasers

Host Mike Nelson continues the cultish comedy cavalcade of biting sarcastic humor that can only be ... "Mystery Science Theater 3000." This time out, Timechasers (a low-budget sci-fi flick that sports an evil CEO) is the B-grade movie schlock that will be expertly (and hilariously) ripped apart at the seams by Nelson and his two robot buddies. Shipped on 01/10/07.

The Devil and Daniel Johnston

In his second film, former commercial director Jeff Feuerzeig tackles the documentary format, introducing the world to Daniel Johnston -- a reclusive musical genius now in the throes of manic depression. Blending up-to-date footage with home movies, archival material and rare audio, Feuerzeig creates a dizzying -- and heartbreaking -- portrait of a man whose inner demons are taking over, one delusion at a time. Shipped on 01/09/07.

The Work of Director Jonathan Glazer

British director Jonathan Glazer has minted his name in the entertainment industry with his phenomenal music videos and visually stunning commercials. His best work is collected in this impressive compendium that includes music videos such as Jamiroquai's memorable "Virtual Insanity" and Massive Attack's "Karma Coma"; television ads for Wrangler, Levis and Stella Artois; and excerpts from his movies such as Sexy Beast and Birth. Shipped on 01/09/07.

The Wild Parrots of Telegraph Hill

This documentary tells the true story of a Bohemian St. Francis of Assisi and his amazing relationship with a flock of wild parrots. Mark Bittner, a homeless street musician in San Francisco, adopts the flock as he searches for meaning in his life. The weird thing is, he's unaware that the wild parrots will bring him everything he needs. The film celebrates urban wildness (human and avian) and links the parrots' antics to human … antics. Shipped on 01/08/07.

APPLE: Macworld launch: 16 to 9 says it's HDTV - Valleywag

this + Hivelogic podcast with John Gruber = BRILLIANT

4Takes interview 4: Paul Dini

writer for many animated shows incl. Tiny Toons, Freakazoid, Batman the Animated Series, Batman Beyond, as well as Lost and comic books

Gamasutra.com - Why Bother With Episodic Games?

that games can be developed like tv shows is a big idea

OpenID Authentication 1.1: 3.4. Smart vs Dumb Mode

apparently Technorati identities don't support dumb mode, so they don't work with my plugin

Tokyo Godfathers

This animated tale tells the unlikely story of three misfit roommates -- Gin (a former professional cyclist), Hana (a transvestite) and Miyuki (a young runaway) -- who find an abandoned baby in a dumpster on Christmas Eve. The wacky group then heads to the big city in search of the baby's parents and must endure a slew of happy people enjoying the season along the way, resulting in a rude awakening for each of the loners. Shipped on 01/02/07.

Why We Fight

Filmed during the Iraq War, this documentary dissects America's military machine with a keen eye to answering the question: Why does America engage in war? Through personal stories of soldiers, government officials, scholars, journalists and innocent victims, the film examines the political and economic interests and ideological factors, past and present, behind American militarism. Winner of the 2005 Sundance Grand Jury Award. Shipped on 01/02/07.

The Bird People in China

A lyrical, visually stunning work that deviates considerably from Takashi Miike's signature gorefests, Bird People in China explores many of his unifying themes; these include that of outsiders in pursuit of happiness in a foreign land, and a complex and unlikely relationship, played out this time between a mobster and a quiet businessman. Shipped on 01/02/07.

notcoming.com | Children of Men

strong praise! opens Friday at Camera 12!

The Old New Thing : Stop the madness: Subdirectories of My Documents

omg big true

The Work of Director Stephane Sednaoui

The Directors Label series spotlights the oeuvre of filmmakers who've transformed advertising, music videos and moviemaking. Featuring Stéphane Sednaoui's work, this volume contains 19 music videos, including R.E.M.'s "Lotus," Alanis Morissette's "Ironic," Garbage's "Queer" and U2's "Mysterious Ways." The bonus material includes interviews with Bono, Björk and the Red Hot Chili Peppers, as well as three short films. Shipped on 12/27/06.

Brick

This unconventional film noir -- set in the halls of a modern-day high school -- marks a promising debut for writer-director Rian Johnson. Teenage loner Brendan Fry is forced to navigate his school's social network when a secret crush turns up dead and the murderer is anyone's guess. Through intense interactions with thespians, band geeks and druggies (including a grown-up Lucas Haas), Brendan works to crack the cliques -- and the case. Shipped on 12/27/06.

Mystery Science Theater 3000: Manos: Hands of Fate

Joel, Crow and Tom Servo subject themselves to a viewing of another kooky classic, all in the name of hilarious comedy. Their subject this time? A horror flick about a family terrorized by a ranch hand and his flock of ghostly zombie women, who have taken up residence at the ranch for some R&R.; Can the family avoid the fate of certain death that faces them? And can the "Mystery Science Theater 3000" crew keep it together? Doubt it ... Shipped on 12/26/06.

Lady Vengeance

The final installment of director Park Chan-wook's revenge trilogy (preceded by Sympathy for Mr. Vengeance and Oldboy) chronicles the efforts of Lee Geum-ja (Lee Yeong-ae) -- known to her cellmates as "the kind Ms. Geum-ja" -- to track down the man who betrayed her. Taking the rap for her accomplice and incarcerated for 13 long years, she plots an elaborate retribution with help from her fellow inmates. Shipped on 12/26/06.

Twitch - [Korean Box Office] I'm A Cyborg, But That's OK To Be Pulled

"Critics praised his experimental storytelling and stylish presentation, but audiences considered it too abstract and unapproachable to follow. In light of Park's fame, "Cyborg" topped box office charts for the first weekend, but it was now not even among

Good Night, and Good Luck

George Clooney's Oscar-nominated docudrama pits TV newsman Edward R. Murrow (David Strathairn) against Sen. Joseph McCarthy and his single-minded crusade to quell the red threat at home. Despite corporate pressure to back off, Murrow and his CBS staff are determined to examine the lies and fear tactics perpetrated by McCarthy during his Communist witch-hunts. The impressive cast includes Robert Downey Jr., Patricia Clarkson and Jeff Daniels. Shipped on 12/22/06.

Compiler Confusion ??? [Archive] - Ubuntu Forums

error: C compiler cannot create executables → apt-get install build-essential

Walk the Line

Among the pantheon of great country singers, Johnny Cash (played here by Joaquin Phoenix) may just be the most enigmatic. James Mangold's film distills Cash's transformation from man to icon -- from his hardscrabble days on an Arkansas farm to Sun Records in Memphis, Tenn., where Cash finally found a way for his talent to come into its own. Reese Witherspoon plays his beloved June, alongside co-stars Robert Patrick and Shelby Lynne. Shipped on 12/20/06.

Mystery Science Theater 3000: Mr. B's Lost Shorts

The menacing Dr. Clayton Forrester serves up yet another piece of rib-tickling torture for his captives: "Mystery Science Theater 3000" host Joel Hodgson and his sidekicks, the robots Crow and Tom. The trio's cinematic victim? A short titled "Mr. B. Natural," a disturbingly strange film about a weird and overly friendly gnome who uses his musical talent to seduce a young boy (which, of course, sends the trio over the moon with witty criticisms). Shipped on 12/19/06.