2

I have some HTML scraped from a site

<div>
 <div id="content1">
 </div>
 <div id="content3">
 </div>
 <div id="content22">
 </div>
</div>

How can I iterate over all the DIVs having ID starting with content?

1 Answer 1

3

The easiest approach would be to use a CSS selector:

soup.select('div[id^=content]')

The ^= syntax specifies that the id attribute value should start with content.

You can get the same result using a regular expression filter passed in as the id argument to element.find_all():

import re

soup.find_all('div', id=re.compile('^content'))

Demo:

>>> from bs4 import BeautifulSoup
>>> sample = '''\
... <div>
...  <div id="content1">
...  </div>
...  <div id="content3">
...  </div>
...  <div id="content22">
...  </div>
... </div>
... '''
>>> soup = BeautifulSoup(sample)
>>> soup.select('div[id^=content]')
[<div id="content1">
</div>, <div id="content3">
</div>, <div id="content22">
</div>]
>>> soup.find_all('div', id=re.compile('^content'))
[<div id="content1">
</div>, <div id="content3">
</div>, <div id="content22">
</div>]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.