utamaro’s blog

誰かの役に立つ情報を発信するブログ

pythonでBeautifulSoupを使ったスクレイピング

pythonでBeautifulSoupを使ったスクレイピング

python3.6.4を使用しています。

必要なライブラリをインストールします。

pip install beautifulsoup4 requests lxml

beautifulsoup4スクレイピングのライブラリ。

requestsはgetとかpostのリクエストに使うライブラリ。

lxmlはhtmlをパースするためのライブラリ。

Beautiful Soup Documentation — Beautiful Soup 4.4.0 documentation

実装例

検索するとヒットするのはurllibを使ってhtmlを取得するやり方だが、requestsも使えます。

大抵は別のAPIを実行したりするため、requestsで統一したほうが良いと考えています。

selectのやり方はドキュメントを読んで試すこと。listで帰ってきます。

jsで言うところのdocument.querySelectorAllと同じです。一件取得したい場合はselect_oneを使います。

from bs4 import BeautifulSoup
import requests

def execute():
    html_text = requests.get(amedas)
    # statusが200なら...などの条件を入れるのが一般的
    soup = BeautifulSoup(html_text.text, "lxml")
    tbl_prefecture_tag = soup.select(selector="#tbl")[0]
    table_cols = tbl_prefecture_tag.select(selector="th['headers'='COL1']")
    # ... ry

if __name__ == "__main__":
    execute()