-2

Is there a select expression for matching tags with multiple classes?

Consider the following HTML snippet:

<div id="top">
    <div class="foo bar"></div>
</div>

I could match it with soup.select('div#top div.foo') or soup.select('div#top div.bar').

But I need both classes to be there.

Is there an expression for that?

fferri
  • 18,285
  • 5
  • 46
  • 95

2 Answers2

8

According to the CSS Spec, the following rule matches any div element whose class attribute has been assigned a list of space-separated values that includes foo and bar:

div.foo.bar

BeautifulSoup also follows this spec, so you can use:

soup.select('div#top div.foo.bar')
rnevius
  • 26,578
  • 10
  • 58
  • 86
  • By the way...this is [right in the documentation](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class) – rnevius Jun 24 '15 at 16:36
2

You can chain class selectors. .foo.bar means only select elements with both class foo and class bar

soup.select('div#top div.foo.bar')