導入
Web制作で使う CSSセレクタ(.class や #id の書き方)を、そのまま要素の指定に使えるのが select です。ブラウザの開発者ツールで得たセレクタを、ほぼそのまま貼れます。
説明
from bs4 import BeautifulSoup
html = """
<div class="card">
<h2 class="title">記事A</h2>
<span class="tag">Python</span>
</div>
<div class="card">
<h2 class="title">記事B</h2>
<span class="tag">Go</span>
</div>
"""
soup = BeautifulSoup(html, "html.parser")
# class="title" の要素を CSS セレクタで全部取る
titles = soup.select(".title")
for t in titles:
print(t.text)
soup.select(".title")… CSSセレクタに当てはまる要素をすべてリストで返します(find_allの CSS版)。soup.select_one(".title")… 最初の1つだけを返します(findの CSS版)。
主なセレクタの書き方は次のとおりです。
| セレクタ | 意味 | 例 |
|---|---|---|
h2 | タグ名で選ぶ | すべての <h2> |
.title | class で選ぶ | class="title" |
#main | id で選ぶ | id="main" |
div.card | タグ+class | class="card" の <div> |
div .title | 子孫(半角スペース) | div の中の .title |
やってみよう
soup.select(".title") を soup.select(".tag") に変えると、タグ名(Python・Go)が取れます。find_all("span", class_="tag") と同じ結果を、CSSセレクタ .tag で書ける点を見比べてみましょう。
演習
上の HTML から、class="tag" の要素をすべて取り出して1行ずつ print してください(select を使うこと)。
ヒント1を見る
for t in soup.select(".tag"): print(t.text)。