Webサイトから
Python に
よる Web スクレイピング とは Web ページから
情報を 自動で 取得する Python の 手法の ことです。 requests + BeautifulSoup の 2 つを 覚えるだけで 始められ、 JavaScript で 生成される サイトは Playwright で 対応します。
TL;DR 早わかりサマリー
- Python スクレイピングは requests + BeautifulSoup の 2 ライブラリで
始められ、 1 時間で 実用スクリプトが書けます - JavaScript で
描画される 動的ページは Selenium / Playwright で対応 - 違法 / 規約違反に
ならない 範囲を 守る ことが 何より重要 - 競合価格監視、
ニュース収集、 商品情報取得、 SNS 分析など 応用範囲は広い
スクレイピングの仕組み
Webスクレイピングとは、
- 対象の
Webページに HTTPリクエストを送信する - 返ってきた
HTMLを 解析 (パース)する - CSSセレクタや
タグ名を 使って、 必要な データを抽出する - 抽出した
データを ファイルや データベースに保存する
Pythonでは、requestsライブラリ、BeautifulSoupライブラリを
環境準備
まず、
ターミナル
pip install requests beautifulsoup4インストールが
Python
import requests
from bs4 import BeautifulSoupこれだけで、
HTMLの 取得と 解析の基本
まずは
Python
import requests
from bs4 import BeautifulSoup
url = "https://example.com"
response = requests.get(url)
response.encoding = response.apparent_encoding
soup = BeautifulSoup(response.text, "html.parser")
print(soup.title.text)requests.get()でBeautifulSoupにsoup.title.textで
CSSセレクタを 使った データ抽出
BeautifulSoupでは、select()メソッドはselect_one()は
Python
# クラス名で要素を取得
items = soup.select(".item-title")
for item in items:
print(item.text.strip())
# IDで要素を取得
header = soup.select_one("#main-header")
# 属性セレクタで絞り込み
links = soup.select("a[href^='https']")
for link in links:
print(link["href"])ブラウザの
実践例:書籍情報を 取得して CSVに保存する
ここでは、
Python
import requests
from bs4 import BeautifulSoup
import csv
import time
url = "https://books.toscrape.com/"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
books = []
for article in soup.select("article.product_pod"):
title = article.select_one("h3 a")["title"]
price = article.select_one(".price_color").text
rating = article.select_one("p.star-rating")["class"][1]
books.append({
"title": title,
"price": price,
"rating": rating
})
# CSVファイルに保存
with open("books.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["title", "price", "rating"])
writer.writeheader()
writer.writerows(books)
print(f"{len(books)}件の書籍データを保存しました")このselect()とselect_one()を
複数ページの データを取得する
多くの
Python
import time
base_url = "https://books.toscrape.com/catalogue/page-{}.html"
all_books = []
for page in range(1, 4): # 1〜3ページを取得
url = base_url.format(page)
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
for article in soup.select("article.product_pod"):
title = article.select_one("h3 a")["title"]
all_books.append(title)
time.sleep(1) # サーバーへの負荷を抑えるために1秒待機
print(f"合計{len(all_books)}件取得")ここでtime.sleep(1)です。
法的・ 倫理的な注意点
スクレイピングは
robots.txt を確認する
ほとんどのrobots.txtというhttps://)にDisallowで
利用規約を確認する
サイトの
サーバーへの 負荷に配慮する
短時間に
個人情報を 収集しない
スクレイピングで
よく ある エラーと対処法
スクレイピングでつまずきやすい
文字化けが
Python
response.encoding = response.apparent_encoding要素がrequestsだけではSeleniumやPlaywrightといった
403エラーが
Python
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers)ただし、
スクレイピングスキルを 活かすには
スクレイピングは
Pythonを
Pythonの
スクレイピングの 基本コード
最も
Python
import requests
from bs4 import BeautifulSoup
# 1. HTML を取得
url = "https://example.com/news"
res = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})
res.encoding = res.apparent_encoding
# 2. パース
soup = BeautifulSoup(res.text, "html.parser")
# 3. 要素を抽出
articles = soup.select("article.news-item")
for article in articles:
title = article.select_one("h2.title").text.strip()
date = article.select_one("time").get("datetime")
link = article.select_one("a").get("href")
print(f"{date} | {title} | {link}")これだけで、
JavaScript 描画ページへの対応
requests / BeautifulSoup では
Python
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto("https://example.com/spa-page")
page.wait_for_selector("h2.title")
titles = page.locator("h2.title").all_text_contents()
for t in titles:
print(t)
browser.close()Playwright は
法律 / 規約 / マナーの 5 原則
これだけは
1. robots.txt を確認 https:// で
2. 利用規約を確認スクレイピング禁止の
3. アクセス間隔を空ける
4. User-Agent を明示自分の
5. 公開 API が
詳しくは Python で
ハンズオン Step-by-Step
Python 3.10 以上の
Step 1. ライブラリを インストール
HTTP 通信用の requests と HTML パーサーの beautifulsoup4 を
ターミナル
pip install requests beautifulsoup4Step 2. 対象ページを取得
example.com を
Python
import requests
res = requests.get("https://example.com")
print(res.status_code)
print(len(res.text))Step 3. BeautifulSoup でパース
HTML を
Python
from bs4 import BeautifulSoup
soup = BeautifulSoup(res.text, "html.parser")
h1 = soup.find("h1")
print(h1.text)Step 4. 複数要素の ループ取得
リンク (a タグ) を
Python
for a in soup.find_all("a"):
print(a.get("href"))Step 5. robots.txt と 利用規約を確認
本番運用するUser-Agent を
JavaScript で
関連リソース
よくある質問
Q. スクレイピングは 違法ですか
A. 違法では
Q. ログインが 必要な サイトは スクレイピングできますか
A. 技術的には
Q. スクレイピングと API、 どちらを 使うべき?
A. API が
Q. JavaScript で 描画される ページの対処法は
A. Selenium / Playwright で
Q. スクレイピングを 業務に 組み込みたい
A. 自社用途 + 規約で
Q. AI スクレイピングサービスは ありますか
A. Browserless、
次に 読むべきリソース
- 学習を
始めたい方 — Python 入門コース - 深く
理解したい方 — Python に よる 業務自動化 - 無料相談したい方 — ゆめさく
エンジニア 無料相談
出典・参考リンク
本記事の
- BeautifulSoup 公式ドキュメント
- requests 公式ドキュメント
- Playwright 公式ドキュメント
- 著作権法 (e-Gov 法令検索)
- 経済産業省
「不正アクセス禁止法ガイド」 - Python 公式ドキュメント
この 記事について
- 公開: 2026-05-28
- 最終更新: 2026-05-28
- カテゴリ: 業務自動化
- 参照した
資料の 版: Python 3.12 / requests 2.32 / BeautifulSoup 4.12 / Playwright 1.45 - 編集ポリシー: 公式ドキュメント・
公的統計を 一次情報として 優先しています。 修正提案や 事実誤認の 指摘は ゆめさく運営まで お寄せください。


