私は、Web からデータをスクレイピングし、HTML テーブルを読み取るために、Python と BeautifulSoup を学習しています。これを Open Office に読み込むと、テーブル #11 であると表示されます。
BeautifulSoup が推奨される選択肢のようですが、特定のテーブルとすべての行を取得する方法を教えていただけますか? モジュールのドキュメントを見ましたが、よくわかりません。オンラインで見つけた例の多くは、必要以上のことを行っているようです。
ベストアンサー1
BeautifulSoup で解析する HTML のチャンクがある場合、これは非常に簡単なはずです。一般的な考え方は、 メソッドを使用してテーブルに移動しfindChildren
、 プロパティを使用してセル内のテキスト値を取得することですstring
。
>>> from BeautifulSoup import BeautifulSoup
>>>
>>> html = """
... <html>
... <body>
... <table>
... <th><td>column 1</td><td>column 2</td></th>
... <tr><td>value 1</td><td>value 2</td></tr>
... </table>
... </body>
... </html>
... """
>>>
>>> soup = BeautifulSoup(html)
>>> tables = soup.findChildren('table')
>>>
>>> # This will get the first (and only) table. Your page may have more.
>>> my_table = tables[0]
>>>
>>> # You can find children with multiple tags by passing a list of strings
>>> rows = my_table.findChildren(['th', 'tr'])
>>>
>>> for row in rows:
... cells = row.findChildren('td')
... for cell in cells:
... value = cell.string
... print("The value in this cell is %s" % value)
...
The value in this cell is column 1
The value in this cell is column 2
The value in this cell is value 1
The value in this cell is value 2
>>>