IT Learning

実践形式でITのお勉強

Python

【Python】BeautifulSoupでtableが最初の数行しか取得できない場合の対処

投稿日:2020年9月7日 更新日:

概要

PythonでWebスクレイピングをするときの定番であるBeautifulsoupですが、tableを取得しようとしたときに最初の数行しか取得できないことがあったのでその対処法についてメモする。

環境

Python 3.7.3

発生事象

以下のようなテーブルがあるとします。

番号名前
1佐藤
2加藤
3伊藤
4後藤

ウェブブラウザのF12で見えているhtmlコードはこのような状態

<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を使った次のようなコードで取得しようとしたところ・・・

import requests
from bs4 import BeautifulSoup

r = requests.get('http://example.com',headers = headers)
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>しか取れてこないという現象が起きました。

<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を使用することで、すべての行を取得できるようになった。(結果は略)

import requests
from bs4 import BeautifulSoup

r = requests.get('http://example.com',headers = headers)
soup = BeautifulSoup(r.content, "lxml")

table = soup.findAll('table',{'class':"test_table"})[0]

rows = table.findAll('tr')
for row in rows:
    print(row)

理由はよくわかりませんが・・・そういうもんだと割り切ってやってこうと思います。

以上

Pythonを一から学ぶのにおすすめの本はコチラ

Related

-Python

執筆者:


  1. […] 【Python】BeautifulSoupでtableが最初の数行しか取得できない場合の対処 […]

【Python】pandasでhtmlのtableをスクレイピング – IT Learning へ返信する コメントをキャンセル

メールアドレスが公開されることはありません。 が付いている欄は必須項目です