Last modified: September 30, 2021

BeautifulSoup: How to Find by CSS selector (.select)

BeautifulSoup provides us select() and select_one() methods to find by css selector.

select(): returns all the matching elements.
select_one(): returns the first matching element.

Find all by selector


.select('css_selector')

In the following example, we"ll find all elements that are inside div.


from bs4 import BeautifulSoup

# html source
html = """
<div>
<h1>This is H1</h1>
<h2>This is H2</h2>
<h3>This is H3</h3>
</div>
"""

# BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')

# Find all by selector
els = soup.select('div > *')


for el in els:
    print(el)

Output:

<h1>This is H1</h1>
<h2>This is H2</h2>
<h3>This is H3</h3>

Find one by selector

Syntax:


.select_one('css_selector')

Let's do like the first example but, now we'll find just the first matching element.


from bs4 import BeautifulSoup

# html source
html = """
<div>
<h1>This is H1</h1>
<h2>This is H2</h2>
<h3>This is H3</h3>
</div>
"""

# BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')

el = soup.select_one('div > *')

print(el)

output:

<h1>This is H1</h1>