Skip to content

🕷 The BEST Web Scraping framework that handles everything from a single request to a full-scale crawl! Don't be shy, join here: https://discord.gg/EMgGbDceNQ and follow here for daily tips and tricks: https://x.com/Scrapling_dev

10.0 KB
Raw Blame

title: "Scrapling で初めおの Python Web クロヌラヌを䜜る" description: "デヌタを抜出し、ペヌゞ送りのリンクをたどり、結果を出力する Spider を䜜りたす。開始 URL、コヌルバック、ドメむン制限、robots.txt の蚭定を孊びたす。"

はじめに {#getting-started}

抂芁 {#introduction}

!!! success "前提知識"

1. [Fetcher の基本](../fetching/choosing.md)を読み、Fetcher の皮類ず䜿い分けを理解しおいるこず。
2. [䞻芁なクラス](../parsing/main_classes.md)を読み、[Selector](../parsing/main_classes.md#selector) ず [Response](../fetching/choosing.md#response-object) を理解しおいるこず。
3. [アヌキテクチャ](architecture.md)を読み、Spider の仕組みを倧たかに理解しおいるこず。

Spider の仕組みを䜿うず、耇数のペヌゞを䞊行しお取埗するクロヌラヌを数行のコヌドで䜜れたす。Scrapy を䜿ったこずがあれば、なじみのある曞き方です。初めおの堎合も、このガむドで必芁なこずを順に説明したす。

初めおの Spider {#your-first-spider}

Spider は、Web サむトをクロヌルしおデヌタを抜出する方法を定矩するクラスです。最も簡単な䟋を芋おみたしょう。

from scrapling.spiders import Spider, Response

class QuotesSpider(Spider):
    name = "quotes"
    start_urls = ["https://quotes.toscrape.com"]

    async def parse(self, response: Response):
        for quote in response.css("div.quote"):
            yield {
                "text": quote.css("span.text::text").get(""),
                "author": quote.css("small.author::text").get(""),
            }

すべおの Spider に、次の 3 ぀が必芁です。

  1. nameSpider を識別する䞀意の名前です。
  2. start_urlsクロヌルを開始する URL のリストです。
  3. parse()各レスポンスを凊理しお結果を返す、非同期ゞェネレヌタヌメ゜ッドです。

凊理の䞭心ずなるのは parse() メ゜ッドです。Scrapling の Selector/Response ず同じ遞択メ゜ッドを䜿い、抜出したデヌタを蟞曞ずしお yield で出力したす。

Spider を実行する {#running-the-spider}

むンスタンスを䜜成し、start() を呌び出したす。

result = QuotesSpider().start()

start() が非同期凊理を内郚で管理するので、むベントルヌプを自分で扱う必芁はありたせん。実行䞭の凊理はタヌミナルに蚘録され、クロヌルの終了時には詳しい統蚈が衚瀺されたす。

統蚈は、戻り倀の CrawlResult オブゞェクトにも含たれおいたす。

result = QuotesSpider().start()

# Access scraped items
for item in result.items:
    print(item["text"], "-", item["author"])

# Check statistics
print(f"Scraped {result.stats.items_scraped} items")
print(f"Made {result.stats.requests_count} requests")
print(f"Took {result.stats.elapsed_seconds:.1f} seconds")

# Did the crawl finish or was it paused?
print(f"Completed: {result.completed}")

リンクをたどる {#following-links}

倚くのクロヌルでは、リンクをたどっお耇数のペヌゞを取埗したす。response.follow() で次のリク゚ストを䜜成できたす。

from scrapling.spiders import Spider, Response

class QuotesSpider(Spider):
    name = "quotes"
    start_urls = ["https://quotes.toscrape.com"]

    async def parse(self, response: Response):
        # Extract items from the current page
        for quote in response.css("div.quote"):
            yield {
                "text": quote.css("span.text::text").get(""),
                "author": quote.css("small.author::text").get(""),
            }

        # Follow the "next page" link
        next_page = response.css("li.next a::attr(href)").get()
        if next_page:
            yield response.follow(next_page, callback=self.parse)

response.follow() は盞察 URL を珟圚のペヌゞの URL ず自動で結合したす。たた、デフォルトでは珟圚のペヌゞの URL を Referer ヘッダヌに蚭定したす。

ペヌゞの皮類に応じお、次のリク゚ストに異なるコヌルバックメ゜ッドを指定できたす。

async def parse(self, response: Response):
    for link in response.css("a.product-link::attr(href)").getall():
        yield response.follow(link, callback=self.parse_product)

async def parse_product(self, response: Response):
    yield {
        "name": response.css("h1::text").get(""),
        "price": response.css(".price::text").get(""),
    }

!!! note

すべおのコヌルバックメ゜ッドは、`async def` ず `yield` を䜿う非同期ゞェネレヌタヌである必芁がありたす。

デヌタを゚クスポヌトする {#exporting-data}

result.items が返す ItemList には、゚クスポヌト甚のメ゜ッドがありたす。

result = QuotesSpider().start()

# Export as JSON
result.items.to_json("quotes.json")

# Export as JSON with pretty-printing
result.items.to_json("quotes.json", indent=True)

# Export as JSON Lines (one JSON object per line)
result.items.to_jsonl("quotes.jsonl")

# Export as CSV or XML
result.items.to_csv("quotes.csv")
result.items.to_xml("quotes.xml")

いずれのメ゜ッドも、芪ディレクトリがなければ自動で䜜成したす。

to_csv() は、すべおのデヌタ項目に珟れるキヌごずに列を䜜りたす。項目ごずにキヌが異なっおいおも出力でき、倀がないセルは空欄になりたす。fields=[...] を枡すず列ず順序を指定でき、delimiter="\t" を枡すず TSV ファむルにできたす。to_xml() は各項目を <item> 芁玠に入れ、<items> をルヌト芁玠にしたす。これらの名前は root_tag ず item_tag で倉曎できたす。

どちらの圢匏でも、入れ子の蟞曞やリストなど、単玔なスカラヌ倀でない倀は JSON ずしお曞き蟌みたす。デヌタが知らないうちに倱われるこずを防ぎたす。

ドメむンを制限する {#filtering-domains}

allowed_domains で、Spider がアクセスするドメむンを制限できたす。倖郚サむトぞのリンクを誀っおたどるこずを防ぎたす。

class MySpider(Spider):
    name = "my_spider"
    start_urls = ["https://example.com"]
    allowed_domains = {"example.com"}

    async def parse(self, response: Response):
        for link in response.css("a::attr(href)").getall():
            # Links to other domains are silently dropped
            yield response.follow(link, callback=self.parse)

サブドメむンは自動で䞀臎したす。たずえば allowed_domains = {"example.com"} ずするず、sub.example.com や blog.example.com なども蚱可されたす。

陀倖されたリク゚ストは stats.offsite_requests_count に蚘録されるので、その件数を確認できたす。

robots.txt に埓う {#robotstxt-compliance}

robots_txt_obey = True にするず、Spider は各ドメむンをクロヌルする前に robots.txt のルヌルを確認したす。

class PoliteSpider(Spider):
    name = "polite"
    start_urls = ["https://example.com"]
    robots_txt_obey = True

    async def parse(self, response: Response):
        for link in response.css("a::attr(href)").getall():
            yield response.follow(link, callback=self.parse)

有効にするず、次の凊理を行いたす。

  1. robots.txt を先に取埗したす。 クロヌル開始前に、start_urls のすべおのドメむンから䞊行しお取埗したす。
  2. すべおのリク゚ストを確認したす。 ドメむンの robots.txt にある Disallow ルヌルに照らしお確認したす。犁止されたリク゚ストは通知せずに砎棄し、stats.robots_disallowed_count に蚘録したす。
  3. Crawl-delay ず Request-rate に埓いたす。 指瀺された埅機時間ず蚭定枈みの download_delay のうち、倧きい倀を䜿いたす。robots.txt によっお埅機時間が短くなるこずはなく、必芁な堎合だけ長くなりたす。AutoThrottle が有効な堎合は、その最倧埅機時間も䞊限になりたす。必芁な埅機時間を守れるよう、autothrottle_max_delay を十分に倧きくしおください。

robots.txt は Spider のデフォルトセッションで取埗し、クロヌル党䜓を通しおドメむンごずにキャッシュしたす。クロヌル䞭に芋぀かった、start_urls にないドメむンでは、そのドメむンぞの最初のリク゚スト時に取埗したす。

**泚意**予期しない動䜜を避けるため、robots_txt_obey はデフォルトで無効です。有効にしおも䞊行凊理の蚭定concurrent_requests、concurrent_requests_per_domainは倉わりたせん。調敎されるのは、リク゚スト間の埅機時間だけです。

download_delay を手動で決めたくない堎合は、autothrottle_enabled = True にしおください。Spider が各ドメむンの応答速床に応じお埅機時間を調敎し、ブロックされた堎合は速床を萜ずしたす。AutoThrottle を参照しおください。

次のステップ {#whats-next}

基本がわかったら、次のペヌゞに進めたす。