【Python】BeautifulSoupのselectの普通の使い方【スクレイピング】
目次
はじめに
PythonのBeautifulSoup4というライブラリはスクレイピングなどで活躍する高レベルなHTML/XMLパーサーです。
これを使うとBeautifulSoup4内部のパーサーを自由に切り替えてHTMLをパースすることが出来ます。
今回はこのBeautifulSoup4のメソッドであるselectメソッドの使い方について解説したいと思います。
ちなみにBeautifulSoup4を利用するには↓のようにpip
でインストールする必要があります。
:::bash
$ pip install beautifulsoup4
selectメソッドの使い方
select
メソッドは↓のようにして使います。
:::python
from bs4 import BeautifulSoup
html = '''
<p>My name is Taro.</p>
<p class="myclass">How do you doing?</p>
<p class="myclass">I'm fine thank you.</p>
'''
soup = BeautifulSoup(html, 'html.parser')
founds = soup.select('.myclass')
print(founds)
出力結果は↓になります。
:::text
[<p class="myclass">How do you doing?</p>, <p class="myclass">I'm fine thank you.</p>]
select
は第1引数のセレクターに従って要素を取得します。
↓の場合はクラス名myclass
を持つ要素を取得しています。
:::python
founds = soup.select('.myclass')
selectメソッドの戻り値
select
メソッドは要素が見つかった場合、bs4.element.ResultSet
で結果を返します。
:::python
founds = soup.select('.myclass')
print(type(founds))
:::text
<class 'bs4.element.ResultSet'>
これはPython組み込みのリストを継承したクラスです。
:::python
class ResultSet(builtins.list)
| ResultSet(source, result=())
|
| A ResultSet is just a list that keeps track of the SoupStrainer
| that created it.
|
| Method resolution order:
| ResultSet
| builtins.list
| builtins.object
| ...
なのでリストのように使うことが出来ます。
:::python
founds = soup.select('.myclass')
print(founds[0])
print(type(founds[0]))
:::text
<p class="myclass">How do you doing?</p>
<class 'bs4.element.Tag'>
各要素にはbs4.element.Tag
が格納されています。
よって、要素にアクセスしてから再度select
などを使うことが出来ます。
もちろんfind
やfind_all
などのメソッドも使えます。
:::python
founds = soup.select('.myclass')
founds[0].select('.next')
select
は要素が見つからなかった場合、空のbs4.element.ResultSet
を返します。
:::python
founds = soup.select('.notfound')
print(len(founds))
:::text
0
selectのセレクターの使い方
select
の肝となるセレクターの使い方です。
Beautiful Soup supports most CSS4 selectors
(BeautifulSoupはほとんどのCSS4セレクターをサポートしています)
とあるように、BeautifulSoupではほとんどのCSSセレクタを使うことが出来ます。
例えばIDの指定は↓のようにします。
:::python
soup.select('#myid')
クラス名を指定して複数の要素を取得するには↓のようにします。
:::python
soup.select('.myclass')
タグ名を指定するには↓のようにします。
:::python
soup.select('p')
タグの親子関係を指定するには↓のようにします。
:::python
soup.select('html body p')
タグのすぐ下のタグを検索するには>
を使います。
:::python
soup.select('html > body')
複数のクラス名をANDで指定したい場合は↓のようにします。
:::python
soup.select('.cat.dog.bird')
探索の収納個数を指定
探索で得る要素の数を指定したい場合はlimit
に整数を指定します。
:::python
soup.select('.myclass', limit=1) # 1個だけ
soup.select('.myclass', limit=2) # 2個だけ
おわりに
セレクターを使ってパースできるというのは、かなり便利だと思います。
みなさんもよきスクレイピングライフを。
アディオス、カウボーイ
関連記事
- 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のブログ