0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

BeautifulSoupでcssセレクタを使い細かく要素を指定する

Posted at

findよりselectのほうがいろいろ使いやすいので
忘れないようにメモ

練習コード

HTML

<div id="a">
    <div id="b">
        <p class="hello">こんにちは</p>
    </div>
    <p class="morning">おはよう</p>
    <p class="night">おやすみ</p>
</div>

python

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "lxml")
#前方一致
print(soup.select('p[class^="he"]'))
#後方一致
print(soup.select('p[class$="ing"]'))
#部分一致
print(soup.select('p[class*="ig"]'))
#直下の子要素のみ
print(soup.select('#a>p'))
#配下の要素
print(soup.select('#a p'))
#以降の要素
print(soup.select('#b~p'))
#隣接の要素
print(soup.select('#b+p'))

出力

[<p class="hello">こんにちは</p>]
[<p class="morning">おはよう</p>]
[<p class="night">おやすみ</p>]
[<p class="morning">おはよう</p>, <p class="night">おやすみ</p>]
[<p class="hello">こんにちは</p>, <p class="morning">おはよう</p>, <p class="night">おやすみ</p>]
[<p class="morning">おはよう</p>, <p class="night">おやすみ</p>]
[<p class="morning">おはよう</p>]
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?