Python と BeautifulSoup を学習して、Web からデータをスクレイピングし、HTML テーブルを読み取ります。それを Open Office に読み込むと、表 #11 であると表示されます。
BeautifulSoup が好ましい選択のようですが、特定のテーブルとすべての行を取得する方法を誰か教えてもらえますか? モジュールのドキュメントを見てきましたが、理解できません。私がオンラインで見つけた例の多くは、必要以上のことをしているようです。
Python と BeautifulSoup を学習して、Web からデータをスクレイピングし、HTML テーブルを読み取ります。それを Open Office に読み込むと、表 #11 であると表示されます。
BeautifulSoup が好ましい選択のようですが、特定のテーブルとすべての行を取得する方法を誰か教えてもらえますか? モジュールのドキュメントを見てきましたが、理解できません。私がオンラインで見つけた例の多くは、必要以上のことをしているようです。
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
>>>