Pythonスクレイピングの基本
PythonによるWebスクレイピングでは主に以下のライブラリを使います。
| ライブラリ | 用途 |
|---|---|
| requests | HTTPリクエスト送信 |
| BeautifulSoup4 | HTML解析 |
| pandas | データ集計・CSV出力 |
| schedule | 定期実行 |
基本的なスクレイピング実装
import requests
from bs4 import BeautifulSoup
import pandas as pd
from datetime import datetime
def scrape_product_price(url: str) -> dict:
headers = {'User-Agent': 'Mozilla/5.0'}
res = requests.get(url, headers=headers, timeout=10)
soup = BeautifulSoup(res.text, 'html.parser')
title = soup.select_one('h1.product-title')
price = soup.select_one('.price-value')
return {
'title': title.text.strip() if title else None,
'price': price.text.strip() if price else None,
'fetched_at': datetime.now().isoformat(),
}
定期実行で価格推移を記録
import schedule, time, csv
def job():
urls = [
'https://example-ec.com/product/aaa',
'https://example-ec.com/product/bbb',
]
results = [scrape_product_price(u) for u in urls]
with open('prices.csv', 'a', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=['title', 'price', 'fetched_at'])
writer.writerows(results)
schedule.every(6).hours.do(job)
while True:
schedule.run_pending()
time.sleep(60)
弊社での活用
弊社では収集したデータをGoogleスプレッドシートに自動連携し、価格の急変や品切れをSlack通知で受け取る仕組みを構築しています。これにより、仕入れのタイミングを逃さず、競合の価格戦略にも素早く対応できています。
価格監視ツールや競合調査の自動化についてご興味があればお気軽にご相談ください。