pythonスクレイピング

https://jutaku-shoene2023.mlit.go.jpのページをスクレイピングして

ディレクトリにcsvファイルで保存するやり方。ページングしてるページを取得する

import csv
from bs4 import BeautifulSoup
import requests
import urllib.parse

# スクレイピングを開始するURLとCSVファイル名を指定kensの47は沖縄県
kens = '47'

start_url = f'https://jutaku-shoene2023.mlit.go.jp/search-for-manufacturer?s=1&prefecture={kens}&public_service_area_prefecture=1&public_business=3&public_project_search_pattern=1&public_project_1=1&public_project_3=1&public_business_reform_search_pattern=1&public_business_reform_4=1&free_word=&operator_number=#search_btn'
output_csv = f'result{kens}.csv'

# ページングされたテーブルからデータを取得してCSVに保存する関数
def scrape_and_save_to_csv(url, csv_filename):
    results = []

    while url:
        r = requests.get(url)
        html_soup = BeautifulSoup(r.content, 'html.parser')

        # テーブルからデータを取得
        table_rows = html_soup.select('tbody tr')
        for row in table_rows:
            cells = row.find_all('td')
            if len(cells) >= 13:  # テーブルの列数に合わせて調整
                area = cells[0].text.strip()

                # 会社名の取得(<a>要素が存在しない場合の処理を追加)
                company_name_cell = cells[1]
                company_name_link = company_name_cell.find('a')
                if company_name_link:
                    company_name = company_name_link.text.strip()
                else:
                    company_name = company_name_cell.text.strip()

                business = cells[2].text.strip()
                search_page = cells[3].text.strip()
                brand_name = cells[4].text.strip()
                construction = cells[5].text.strip()
                reform = cells[6].text.strip()
                lease = cells[7].text.strip()
                energy = cells[8].text.strip()
                company_number = cells[9].text.strip()
                registration_date = cells[10].text.strip()

                # 問合先の取得
                contact_cell = cells[11]
                if contact_cell.find('a'):
                    contact = contact_cell.find('a')['href']
                    # 絶対URLに変換
                    absolute_contact = urllib.parse.urljoin(url, contact)
                else:
                    contact = contact_cell.text.strip()
                note = cells[12].text.strip()
                if not note:
                    note = '-'
                results.append({
                    '営業エリア': area,
                    '登録事業者名': company_name,
                    '登録事業': business,
                    '事業所(検索ページ)': search_page,
                    '店舗・ブランド名': brand_name,
                    '建設業': construction,
                    'リフォーム団体登録': reform,
                    'リース事業': lease,
                    'エネルギー小売事業者': energy,
                    '登録事業者番号': company_number,
                    '登録日': registration_date,
                    '問合先': contact,
                    '備考': note
                })

        # 次のページへのリンクを取得
        next_page_link = html_soup.find('a', {'class': 'pagination-button--next'})
        if next_page_link:
            # 次のページへの相対URLを取得
            next_page_url = next_page_link['href']
            
            # 現在のページのURLと結合して絶対URLを生成
            url = urllib.parse.urljoin(url, next_page_url)
        else:
            url = None

    # データをCSVファイルに保存
    with open(csv_filename, 'w', newline='', encoding='utf-8') as csv_file:
        fieldnames = ['営業エリア', '登録事業者名', '登録事業', '事業所(検索ページ)', '店舗・ブランド名',
                      '建設業', 'リフォーム団体登録', 'リース事業', 'エネルギー小売事業者', '登録事業者番号',
                      '登録日', '問合先', '備考']
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(results)

# スクレイピングを実行
scrape_and_save_to_csv(start_url, output_csv)

# スクレイピングが終了したことを表示
print(kens)
print("OK")

沖縄県の業者データがcsvで取得できる。

47都道府県を回せば全部取れるんじゃね。

コメント

hage01

2008年頃からワードプレス使ってますヴァージョンは2.6か2.8かだったかな?

hage01をフォローする
タイトルとURLをコピーしました