1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonでWebスクレイピングする基本【requests + BeautifulSoup】

1
Posted at

はじめに

「Webサイトの情報を定期的にチェックして記録したい」
「一覧ページのデータをまとめて取得したい」

こういった作業を自動化できるのが Webスクレイピングです。この記事では、Pythonの定番ライブラリ requestsBeautifulSoup を使った基本的なスクレイピングの手順を解説します。

※ スクレイピングにはマナーとルールがあります。記事の後半で必ず守るべき点をまとめているので、最後まで読んでから実践してください。

準備

pip install requests beautifulsoup4
  • requests:Webページを取得するライブラリ
  • BeautifulSoup:取得したHTMLを解析するライブラリ

Step 1:Webページを取得する

import requests

url = 'https://example.com'

# User-Agentを指定してアクセス(誰がアクセスしているか明示するのがマナー)
headers = {
    'User-Agent': 'Mozilla/5.0 (compatible; MyScraper/1.0)',
}

response = requests.get(url, headers=headers)
response.encoding = response.apparent_encoding  # 文字化け対策

# ステータスコードを確認(200なら成功)
print(response.status_code)
print(response.text[:500])  # HTMLの先頭500文字

Step 2:HTMLを解析する

取得したHTMLを BeautifulSoup に渡すと、要素を簡単に取り出せるようになります。

from bs4 import BeautifulSoup

soup = BeautifulSoup(response.text, 'html.parser')

# タイトルを取得
title = soup.title.text
print(title)

# 最初のh1タグを取得
h1 = soup.find('h1')
print(h1.text)

Step 3:要素を抽出する

タグ・クラス・IDで探す

# 特定のクラスを持つ要素を1つ取得
element = soup.find('div', class_='price')
print(element.text)

# 特定のクラスを持つ要素を全て取得(リストで返る)
items = soup.find_all('li', class_='item')
for item in items:
    print(item.text)

# IDで取得
main = soup.find(id='main-content')

CSSセレクタで探す(select)

CSSセレクタが使えると、より柔軟に要素を指定できます。

# CSSセレクタで複数要素を取得
titles = soup.select('div.article h2.title')
for t in titles:
    print(t.text.strip())

# 属性を取得(リンクのURLなど)
links = soup.select('a.external')
for link in links:
    print(link.get('href'))

Step 4:取得したデータをCSVに保存する

import csv
import requests
from bs4 import BeautifulSoup

url = 'https://example.com/products'
headers = {'User-Agent': 'Mozilla/5.0 (compatible; MyScraper/1.0)'}

response = requests.get(url, headers=headers)
response.encoding = response.apparent_encoding
soup = BeautifulSoup(response.text, 'html.parser')

# 商品名と価格を取得する例
products = []
for item in soup.select('div.product'):
    name  = item.select_one('.name').text.strip()
    price = item.select_one('.price').text.strip()
    products.append([name, price])

# CSVに保存
with open('products.csv', 'w', newline='', encoding='utf-8-sig') as f:
    writer = csv.writer(f)
    writer.writerow(['商品名', '価格'])  # ヘッダー
    writer.writerows(products)

print(f'{len(products)}件を保存しました')

複数ページを巡回する

import time
import requests
from bs4 import BeautifulSoup

headers = {'User-Agent': 'Mozilla/5.0 (compatible; MyScraper/1.0)'}

for page in range(1, 6):  # 1〜5ページ
    url = f'https://example.com/list?page={page}'
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')

    # ここでデータ抽出処理
    print(f'{page}ページ目を処理しました')

    time.sleep(2)  # ★ 重要:次のアクセスまで2秒待つ

【重要】スクレイピングのマナーとルール

スクレイピングは便利ですが、やり方を間違えると相手のサーバーに負荷をかけたり、規約違反になったりします。 以下を必ず守ってください。

① robots.txt を確認する

サイトの https://対象サイト/robots.txt に、クロールを許可/禁止する範囲が書かれています。Disallow で指定された場所へのアクセスは避けます。

② 利用規約を確認する

サイトによっては規約でスクレイピングを明確に禁止しています。特にログインが必要なページや会員向けコンテンツは慎重に。

③ アクセス間隔を空ける

短時間に大量アクセスするとサーバーに負荷をかけ、業務妨害とみなされる可能性があります。time.sleep() で必ず間隔を空ける(最低1〜2秒)。

④ 取得したデータの扱いに注意する

著作権のあるコンテンツの再配布や、個人情報の収集は法的問題になります。取得は個人利用や分析の範囲にとどめるのが安全です。

⑤ APIがあればAPIを使う

多くのサービスは公式APIを提供しています。APIがある場合はスクレイピングより安定的で規約的にも安全なので、まずAPIを探しましょう。


まとめ

  • requests でページ取得、BeautifulSoup で解析
  • find / find_all / select で要素を抽出
  • 取得データは utf-8-sig でCSV保存すると文字化けしない
  • 必ず robots.txt・利用規約を確認し、アクセス間隔を空ける
  • 公式APIがあればそちらを優先する

マナーを守れば、スクレイピングは情報収集を大幅に効率化してくれる強力な手段です。


データ収集・自動化のご相談

「Webの情報を定期収集したい」「取得したデータを分析・可視化したい」などのご相談を受け付けています。適法な範囲で、目的に合った仕組みをご提案します。

🌐 https://datarou.com

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?