beautifulsoupでスクレイピングしてみる

2020年12月22日

サイトからデータを収集するとき、手入作業では大変なのでpythonにやってもらいましょう。
ということで今回はスクレいピングについて書いてみたいと思います。

ターゲットとなるのは、このページの下のテーブルです。

言語 コーダー呼称
Python パイソニスタ
PHP ペチパー
Java SIer

 

早速必要なライブラリをインストールしていきます。


#URLを読み込む為のライブラリ
 pip3 install requests
#スクレイピングの為のライブラリ
 pip3 install beautifulsoup4

コードは下記の通りです。


import requests
from bs4 import BeautifulSoup

#サイトにリクエストを送りレスポンスを受ける
request = requests.get('http://houdoukyokucho.com/2020/03/24/post-533/')

#レスポンスからHTMLをオブジェクトとして取得する
soup = BeautifulSoup(request.text, 'html.parser')

#テーブルを指定
first_table = soup.find_all('table')[0]
rows        = first_table.find_all('tr') 

collable_list = []

for row_index, row in enumerate(rows):
    #最初のカラムは項目なのでスキップする
    if row_index == 0:
        continue
    cells = row.find_all('td')
    collable_dict = {}
    for cell_index, cell in enumerate(cells):
        if cell_index == 0:
            collable_dict['lang'] = cell.get_text()
        elif cell_index == 1:
            collable_dict['collable'] = cell.get_text()
    collable_list.append(collable_dict)
print(collable_list)

実行結果は下記の通りです。
配列の中に列ごとの「辞書」が格納されています。


$ python3.6 beautifulsoup.py 
[{'lang': 'Python', 'collable': 'パイソニスタ'}, {'lang': 'PHP', 'collable': 'ペチパー'}, {'lang': 'Java', 'collable': 'SIer'}]
YouTube

2020年12月22日