高度な Python Web スクレーパー

Python で高度な Web スクレイパーを構築します。ページ データの抽出、ユーザー エージェント ブロックの処理、レート制限の管理、出力の構造化について学びます。

エディターで試してみる

概要

Web スクレイピングには、プログラムによって Web ページを取得し、その HTML 構造を解析して特定のデータを抽出することが含まれます。 Python では、これは伝統的に「requests」と「BeautifulSoup」を使用して実現されます。

高度なスクレーパーには堅牢な構成が必要です。ページをリクエストするだけではブロックや IP 禁止が発生する可能性があり、カスタム ユーザー エージェントなどのヘッダーのカスタマイズが必要になり、ランダムな遅延間隔が発生します。

このインタラクティブな例は、検証を使用したモック データのスクレイピングを模倣しています。ネストされたコンテナーを検索し、ネットワーク タイムアウトを処理し、出力データをクリーンなリストに構造化する方法を示します。

コードと実行の出力

カスタム ヘッダー、タイムアウト管理、HTML パーサー構造を備えた Web スクレイピング ルーチン。

import requests
from bs4 import BeautifulSoup
import time

def scrape_quotes():
    # Mock URL designed for scraping practice
    url = "https://quotes.toscrape.com/"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
    }
    
    print(f"Initiating request to: {url}...")
    try:
        # Request with timeout protection
        response = requests.get(url, headers=headers, timeout=5)
        response.raise_for_status()
        
        soup = BeautifulSoup(response.text, "html.parser")
        quotes = soup.find_all("div", class_="quote", limit=3)
        
        results = []
        for q in quotes:
            text = q.find("span", class_="text").text
            author = q.find("small", class_="author").text
            tags = [t.text for t in q.find_all("a", class_="tag")]
            results.append({
                "quote": text,
                "author": author,
                "tags": tags
            })
            
        print("Scrape completed successfully!\n")
        for idx, item in enumerate(results):
            print(f"Quote {idx+1}: {item['quote']}")
            print(f"  Author: {item['author']}")
            print(f"  Tags:   {', '.join(item['tags'])}\n")
            
    except requests.exceptions.RequestException as e:
        print(f"Network error occurred: {e}")

scrape_quotes()
端子出力
Initiating request to: https://quotes.toscrape.com/...
Scrape completed successfully!

Quote 1: “The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”
  Author: Albert Einstein
  Tags:   change, deep-thoughts, thinking

Quote 2: “It is our choices, Harry, that show what we truly are, far more than our abilities.”
  Author: J.K. Rowling
  Tags:   abilities, choices

Quote 3: “There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”
  Author: Albert Einstein
  Tags:   inspirational, life, live, miracle

段階的な実装

  • ショッピング カタログ全体での価格の監視と追跡
  • フォーラムからレビューデータを収集することによる感情分析
  • 学術研究データセットの作成

よくある質問

robots.txt とは何ですか?

ドメインのルートに配置され、検索ロボットおよびクローラーがクロールを許可または禁止されているパスを示すテキスト ファイル。スクレイパーを作成する前に必ず読んでください。

JavaScript を介して動的にレンダリングされたページをスクレイピングするにはどうすればよいですか?

標準リクエストは静的 HTML のみをフェッチします。 Javascript を多用するページを解析するには、Playwright や Selenium などのブラウザ自動化ツールを使用する必要があります。

関連トピック