[TIP] Testing HTML using CSS selectors

Simon Willison simon at simonwillison.net
Thu Mar 1 04:43:42 PST 2007

Hi all,

I've been testing my current Web project using BeautifulSoup.
BeautifulSoup is a wonderful tool, but then I heard about
assert_select in Rails:


Running assertions against an HTML document using CSS selectors was
just too good an idea to miss, so I've put together a simple extension
to BeautifulSoup that allows you to do exactly that:


Here's some example lines from one of my tests:

response = client.get('/test/show_messages/')
soup = Soup(response.content)
self.assert_(soup.findSelect('div#messages'), 'No messages div')
lis = soup.findSelect('div#messages ul li')
self.assertEqual(len(lis), 3)
self.assertEqual(lis[0].string, 'Test message one')
self.assertEqual(lis[1].string, 'Test message two')
self.assertEqual(lis[2].string, 'Test message three')

My implementation is pretty limited at the moment - it does class, ID
and attribute selectors but doesn't do child selectors or
pseudo-selectors yet. I eventually plan to have it cover everything
from CSS 2.1, as described here:




More information about the testing-in-python mailing list