特定のWebサイトからニュースや価格情報を定期抽出し、クレンジングした上でCSV出力およびNotionデータベースへ自動保存するスクレイピングパイプラインです。
Python
import os
import time
import requests
from bs4 import BeautifulSoup
import pandas as pd
# 1. 静的HTMLの抽出(第5章)
def fetch_latest_news():
url = "https://news.ycombinator.com/"
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
articles = []
for item in soup.select(".titleline > a"):
articles.append({
"title": item.get_text(),
"url": item.get("href")
})
return articles
# 2. クレンジングとCSV出力(第2章・第5章)
def save_to_csv(articles, filename="latest_news.csv"):
df = pd.DataFrame(articles)
df.dropna(inplace=True)
df.to_csv(filename, index=False, encoding="utf-8-sig")
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {len(df)} 件のデータを保存しました。")
if __name__ == "__main__":
news_data = fetch_latest_news()
save_to_csv(news_data)

コメント