【Python】BeautifulSoupでclassを指定して要素を取得する方法【スクレイピング】
目次
はじめに
BeautifulSoupの使い方を解説しています。
class_を指定して要素を取得する方法
BeautifulSoupで特定のクラス名を指定して要素を取得したい場合があります。
例えば↓のようなHTMLがあった場合です。
<p class="dog">I am dog!</p> <p class="cat">I am cat!</p> <p class="bird">I am bird 1!</p> <p class="bird">I am bird 2!</p>
↑のp
タグの一覧からクラス名にcat
が含まれているタグを取得したい場合、↓のようにします。
from bs4 import BeautifulSoup html = ''' <p class="dog">I am dog!</p> <p class="cat">I am cat!</p> <p class="bird">I am bird 1!</p> <p class="bird">I am bird 2!</p> ''' soup = BeautifulSoup(html, 'html.parser') found = soup.find('p', class_='cat') print(found.text)
↑のコードを実行すると↓のような結果になります。
I am cat!
注目したいのが↓のタグを取得している所です。
cat = soup.find('p', class_='cat')
BeautifulSoupオブジェクトのfind
メソッドの第1引数に要素名を指定すると、その要素を取得することが出来ます。
さらにfind
メソッドのキーワード引数class_
に取得したいクラス名を指定すると、指定のクラス名を持つ要素を取得することが出来ます。
もちろんこのclass_
属性はfind_all
メソッドでも使うことが出来ます。
birds = soup.find_all('p', class_='bird') print(birds)
↑のコードの実行結果は↓のようになります。
[<p class="bird">I am bird 1!</p>, <p class="bird">I am bird 2!</p>]
複数のクラス名でAND検索
find
メソッドなどのclass_
属性には複数のクラス名を指定することが出来ます。
from bs4 import BeautifulSoup html = ''' <p class="dog">I am dog!</p> <p class="cat bird">I am cat bird!</p> ''' soup = BeautifulSoup(html, 'html.parser') found = soup.find('p', class_='cat bird') print(found)
↑のコードを実行すると↓のような結果になります。
<p class="cat bird">I am cat bird!</p>
↑の場合、cat
かつbird
のクラス名を持つ要素を取得します。
しかし、たとえばclass_='bird cat'
のようにすると取得できません。
順不同のAND検索をしたい場合はselect
メソッドを使うといいでしょう。
found = soup.select('p.cat.bird') print(found)
↑のコードを実行すると↓のような結果になります。
[<p class="cat bird">I am cat bird!</p>]
複数のクラス名でOR検索
find_all
のclass_
属性にリストなどを渡すとOR検索が可能です。
from bs4 import BeautifulSoup html = ''' <p class="cat">I am dog!</p> <p class="cat bird">I am cat bird!</p> ''' soup = BeautifulSoup(html, 'html.parser') found = soup.find_all('p', class_=['cat', 'bird']) print(found)
↑のコードを実行すると↓のような結果になります。
[<p class="cat">I am dog!</p>, <p class="cat bird">I am cat bird!</p>]
↑の場合、クラス名にcat
かbird
を含む要素を取得しています。
attrsでclassを指定して要素を取得する方法
find
, find_all
ではclass_
属性の他にattrs
属性も使うことが出来ます。
これにclass
を指定すると指定したクラス名の要素を取得することが可能です。
cat = soup.find('p', attrs={ 'class': 'cat' }) print(cat) birds = soup.find_all('p', attrs={ 'class': 'cat' }) print(birds)
おわりに
BeautifulSoupでは色々な方法でクラス名を指定することが出来ました。
柔軟でふわふわで美しいパーサーですね。
皆さんも良きスクレイピング・ライフを。
アディオス、カウボーイ
関連記事
- BeautifulSoupの美しさを知りませんでした。実際に使ってみるまでは - narupoのブログ
- Python3 + Selenium + BeautifulSoup4: Chromeドライバを利用した実装例 - narupoのブログ
- 【Python】BeautifulSoupでclassを指定して要素を取得する方法【スクレイピング】 - narupoのブログ
- 【Python】BeautifulSoupのfindとfind_allの使い方【スクレイピング】 - narupoのブログ
- 【Python】BeautifulSoupのselectの普通の使い方【スクレイピング】 - narupoのブログ
- 【Python】BeautifulSoupでhrefの値を取得する【スクレイピング】 - narupoのブログ
姉妹ブログを見に行く。