Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's really very easy using keyword arguments.</p> <pre><code>&gt;&gt;&gt; from BeautifulSoup import BeautifulSoup &gt;&gt;&gt; soup = BeautifulSoup('''&lt;div class="entry"&gt; ... &lt;h3 class="foo"&gt; ... &lt;a href="http://www.example.com/blog-entry-slug" ... rel="bookmark"&gt;Blog Entry&lt;/a&gt; ... &lt;/h3&gt; ... ... ... &lt;/div&gt; ... ''') &gt;&gt;&gt; soup.find('div', 'entry').find(rel='bookmark').text u'Blog Entry' </code></pre> <p>Alternately,</p> <pre><code>&gt;&gt;&gt; for entry in soup('div', 'entry'): ... for bookmark in entry(rel='bookmark'): ... print bookmark.text ... Blog Entry </code></pre> <p>You can also use <code>attrs</code> to effect a selector of <code>.entry</code> rather than <code>div.entry</code>:</p> <pre><code>&gt;&gt;&gt; for entry in soup(attrs={'class': 'entry'}): ... for bookmark in entry(rel='bookmark'): ... print bookmark.text ... Blog Entry </code></pre> <p>(Note calling the soup or part of the soup is equivalent to <code>.findAll()</code>.)</p> <p>As a list comprehension, that's <code>[b.text for e in soup('div', 'entry') for b in e(rel='bookmark')]</code> (produces <code>[u'Blog Entry']</code>).</p> <p>If you are wanting real CSS3 selectors, I'm not aware of any such thing for BeautifulSoup. All (or if not quite, almost all) of it can be done with simple nesting, conditions and regular expressions (you could just as well use <code>entry(rel=re.compile('^bookmark$'))</code>). If you want something like that, consider it your next project! It could be useful for flattening code and making it more understandable to web people.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload