CSS selectors

select and select_one — the CSS you already know.

select returns a list. select_one returns the first match or None. The syntax is CSS: div#stock, ul.products li, a[href].

Goal

Select by id, class, and attribute, then take the first match.

select

html = """
<main id="stock">
  <ul class="products">
    <li class="item">Chai</li>
    <li class="item sold-out">Samosa</li>
  </ul>
  <a href="/nairobi/">Nairobi</a>
</main>
"""
soup = BeautifulSoup(html, "html.parser")
print(soup.select("#stock h1"))
print([li.get_text() for li in soup.select("li.item")])
print([a.get("href") for a in soup.select("a[href]")])

select_one

html = """
<nav>
  <a href="/nairobi/">Nairobi</a>
  <a href="/mombasa/">Mombasa</a>
</nav>
"""
soup = BeautifulSoup(html, "html.parser")
first = soup.select_one("nav a")
print(first.get_text(), first.get("href"))
print(soup.select_one("table"))

select needs the soupsieve package. The workbench already installed it with Beautiful Soup.

Tip

select("tr td:nth-of-type(1)") is handy on tables. Keep selectors simple — this parser is not a full browser.