前回の記事では、Beautiful Soupを使った基本的なウェブスクレイピングの方法を紹介しました。
今回は、実用的で高度なテクニックについて解説します。
1. 複数ページにまたがるデータの取得
多くのウェブサイトでは、データが複数のページにまたがっています。
これをスクレイピングするために、ページネーションを処理する方法を紹介します。
import requests
from bs4 import BeautifulSoup
# 基本URL
base_url = 'https://example.com/page/'
# ページ数の設定
num_pages = 5
# 各ページのデータを取得
for page in range(1, num_pages + 1):
url = f"{base_url}{page}"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# ページごとのデータを解析
items = soup.find_all('div', class_='item')
for item in items:
title = item.find('h2').string
print(f"ページ {page} のアイテム: {title}")
2. JavaScriptで生成されたコンテンツの取得
一部のウェブサイトでは、コンテンツがJavaScriptによって動的に生成されます。
これを取得するために、Seleniumなどのライブラリを使用します。
from selenium import webdriver
from bs4 import BeautifulSoup
# WebDriverの設定
driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
# URLの指定
url = 'https://example.com'
# ページを開く
driver.get(url)
# ページの読み込みを待つ(必要に応じて調整)
driver.implicitly_wait(10)
# ページソースの取得
html = driver.page_source
# BeautifulSoupで解析
soup = BeautifulSoup(html, 'html.parser')
# 必要なデータを抽出
items = soup.find_all('div', class_='item')
for item in items:
title = item.find('h2').string
print(f"アイテム: {title}")
# ドライバーを閉じる
driver.quit()
3. データのクリーニングと保存
スクレイピングしたデータをそのまま使用するのではなく、データを整形し、CSVやExcelに保存する方法を紹介します。
import csv
import pandas as pd
# サンプルデータ
data = [
{'title': 'Item 1', 'price': '$10'},
{'title': 'Item 2', 'price': '$20'},
{'title': 'Item 3', 'price': '$30'}
]
# CSVに保存
with open('output.csv', 'w', newline='') as csvfile:
fieldnames = ['title', 'price']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for row in data:
writer.writerow(row)
# Excelに保存
df = pd.DataFrame(data)
df.to_excel('output.xlsx', index=False)
4. 認証が必要なウェブサイトへのアクセス
認証が必要なウェブサイトからデータを取得する方法を紹介します。
ここでは、Requestsライブラリを使った例を示します。
# 認証情報の設定
auth = ('username', 'password')
# URLの指定
url = 'https://example.com/login'
# 認証付きのGETリクエスト
response = requests.get(url, auth=auth)
# ステータスコードの確認
if response.status_code == 200:
print("認証に成功しました")
# BeautifulSoupで解析
soup = BeautifulSoup(response.content, 'html.parser')
print(soup.prettify())
else:
print("認証に失敗しました")
5. プロキシを使ったスクレイピング
特定のウェブサイトでは、アクセス制限やIP制限がかかっていることがあります。
この場合、プロキシを使ってリクエストを送信します。
# プロキシの設定
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080',
}
# URLの指定
url = 'https://example.com'
# プロキシ付きのGETリクエスト
response = requests.get(url, proxies=proxies)
# ステータスコードの確認
print(f"ステータスコード: {response.status_code}")
print(f"レスポンス内容: {response.text}")
以上
前回