import requests
from bs4 import BeautifulSoup
import csv
import time
import os

# 初期URL
base_url = "https://www.baitoru.com"
#start_url = "https://www.baitoru.com/kanto/jlist/productionstaff-linework-computerproduct-carproduct-ceproduct-foodproduct-check/"
start_url = "https://www.baitoru.com/kanto/jlist/creative/"

# ヘッダー情報 (User-Agentを設定)
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}

# CSVファイル名
csv_filename = "C:/temp/baitoru.csv"

# 初回のみヘッダーを書き込む
if not os.path.exists(csv_filename):
    with open(csv_filename, mode="w", newline="", encoding="utf-8") as file:
        writer = csv.writer(file)
        writer.writerow(["タイトル", "見出し"])  # ヘッダー行

# 現在のページURL
current_url = start_url
page_number = 1

while current_url:
    # ページ取得
    response = requests.get(current_url, headers=headers)
    response.raise_for_status()  # エラーがあれば例外を発生させる
    soup = BeautifulSoup(response.text, "html.parser")

    # 各求人情報を取得
    new_data = []
    for job in soup.select(".list-jobListDetail"):
        title_elem = job.select_one(".pt03 dl:first-of-type dd")
        headline_elem = job.select_one(".pt02b .li01")

        title = title_elem.get_text(strip=True) if title_elem else "N/A"
        headline = headline_elem.get_text(strip=True) if headline_elem else "N/A"

        new_data.append([title, headline])

    # CSVに追記
    with open(csv_filename, mode="a", newline="", encoding="utf-8") as file:
        writer = csv.writer(file)
        writer.writerows(new_data)

    print(f"ページ {page_number} のデータを CSV に追加しました。")

    # 次ページの判定
    page_number += 1
    next_page_url = f"{start_url}{page_number}/"

    # 実際にそのURLが存在するか確認
    next_response = requests.get(next_page_url, headers=headers)
    if next_response.status_code == 200:
        current_url = next_page_url  # 次のページへ移動
        time.sleep(1)  # サーバー負荷を下げるため1秒待機
    else:
        break  # 次ページが存在しない場合ループ終了

print(f"データを {csv_filename} に保存しました。")
