【Python】BeautifulSoupでtableが最初の数行しか取得できない場合の対処
概要
PythonでWebスクレイピングをするときの定番であるBeautifulsoupですが、tableを取得しようとしたときに最初の数行しか取得できないことがあったのでその対処法についてメモする。
環境
Python 3.7.3
発生事象
以下のようなテーブルがあるとします。
番号 | 名前 |
1 | 佐藤 |
2 | 加藤 |
3 | 伊藤 |
4 | 後藤 |
ウェブブラウザのF12で見えているhtmlコードはこのような状態
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | < table class = "test_table" > < thead > < tr > < th >名前</ th > < th >氏名</ th > </ tr > </ thead > < tbody > < tr > < td >1</ td > < td >佐藤</ td > </ tr > </ tbody > < tbody > < tr > < td >2</ td > < td >加藤</ td > </ tr > </ tbody > < tbody > < tr > < td >3</ td > < td >伊藤</ td > </ tr > </ tbody > < tbody > < tr > < td >4</ td > < td >後藤</ td > </ tr > </ tbody > </ table > |
これをBeautifulSoupを使った次のようなコードで取得しようとしたところ・・・
01 02 03 04 05 06 07 08 09 10 11 | import requests from bs4 import BeautifulSoup soup = BeautifulSoup(r.content, "html.parser" ) table = soup.findAll( 'table' ,{ 'class' : "test_table" })[ 0 ] rows = table.findAll( 'tr' ) for row in rows: print (row) |
実行結果
なぜか最初の数行分の<tr>しか取れてこないという現象が起きました。
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 | <tr> <th>名前</th> <th>氏名</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>佐藤</td> </tr> </tbody> <tbody> <tr> <td>2</td> <td>加藤</td> </tr> </tbody> |
対処法
試した結果、BeautifulSoupでhtml.parserではなくlxmlを使用することで、すべての行を取得できるようになった。(結果は略)
01 02 03 04 05 06 07 08 09 10 11 | import requests from bs4 import BeautifulSoup soup = BeautifulSoup(r.content, "lxml" ) table = soup.findAll( 'table' ,{ 'class' : "test_table" })[ 0 ] rows = table.findAll( 'tr' ) for row in rows: print (row) |
理由はよくわかりませんが・・・そういうもんだと割り切ってやってこうと思います。
以上
Pythonを一から学ぶのにおすすめの本はコチラ
1件の返信
[…] 【Python】BeautifulSoupでtableが最初の数行しか取得できない場合の対処 […]