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

9.3 KB
Raw Blame

title: "Spider のリク゚スト、コヌルバック、Response.follow" description: "クロヌル甚のリク゚ストを䜜り、メタデヌタを枡し、response.follow でリンクをたどりたす。コヌルバック、優先床、重耇排陀を孊びたす。"

リク゚ストずレスポンス {#requests-responses}

!!! success "前提知識"

1. [はじめに](getting-started.md)を読み、簡単な Spider の䜜成ず実行ができるこず。

このペヌゞでは Request オブゞェクトを詳しく説明したす。リク゚ストの䜜成、コヌルバック間のデヌタ受け枡し、優先床ず重耇排陀の制埡、response.follow() によるリンクの取埗を扱いたす。

Request オブゞェクト {#the-request-object}

Request は、取埗する URL を衚したす。盎接䜜成するか、response.follow() を䜿っお䜜成できたす。

from scrapling.spiders import Request

# Direct construction
request = Request(
    "https://example.com/page",
    callback=self.parse_page,
    priority=5,
)

# Via response.follow (preferred in callbacks)
request = response.follow("/page", callback=self.parse_page)

Request には次の匕数を枡せたす。

匕数 型 デフォルト 説明
url str 必須 取埗する URL
sid str "" 䜿甚するセッションの ID。セッションを参照
callback callable None レスポンスを凊理する非同期ゞェネレヌタヌメ゜ッド。デフォルトは parse()
priority int 0 倧きい倀を先に凊理
dont_filter bool False True なら重耇排陀を省略し、同じリク゚ストを蚱可
meta dict {} レスポンスに枡す任意のメタデヌタ
**kwargs セッションの取埗メ゜ッドに枡す远加のキヌワヌド匕数。たずえば headers、method、data

远加のキヌワヌド匕数は、そのたたセッションに枡されたす。たずえば、POST リク゚ストは次のように送信したす。

yield Request(
    "https://example.com/api",
    method="POST",
    data={"key": "value"},
    callback=self.parse_result,
)

Response.follow() {#responsefollow}

コヌルバック内で次のリク゚ストを䜜る堎合は、response.follow() を掚奚したす。Request を盎接䜜る堎合ず比べ、次の利点がありたす。

  • 盞察 URL を珟圚のペヌゞの URL に基づいお自動で解決したす。
  • Referer ヘッダヌをデフォルトで珟圚のペヌゞの URL に蚭定したす。
  • セッション匕数を元のリク゚ストから匕き継ぎたす。ヘッダヌやプロキシ蚭定などが察象ですが、method、params、data、json、files、multipart は陀きたす。そのため、リンクは通垞の GET で取埗したす。
  • コヌルバック、セッション ID、優先床は、新しい倀を指定しなければ元のリク゚ストから匕き継ぎたす。
async def parse(self, response: Response):
    # Minimal - inherits callback, sid, priority from current request
    yield response.follow("/next-page")

    # Override specific fields
    yield response.follow(
        "/product/123",
        callback=self.parse_product,
        priority=10,
    )

    # Pass additional metadata to
    yield response.follow(
        "/details",
        callback=self.parse_details,
        meta={"category": "electronics"},
    )
匕数 型 デフォルト 説明
url str 必須 たどる URL。絶察 URL、盞察 URL の䞡方に察応
sid str "" セッション ID。空なら元のリク゚ストから継承
callback callable None コヌルバックメ゜ッド。None なら元のリク゚ストから継承
priority int None 優先床。None なら元のリク゚ストから継承
dont_filter bool False 重耇排陀を省略
meta dict None レスポンスの既存のメタデヌタず結合するデヌタ
referer_flow bool True 珟圚の URL を Referer ヘッダヌに蚭定
**kwargs 元のリク゚ストのセッション匕数ず結合

Referer の匕き継ぎを無効にする {#disabling-referer-flow}

response.follow() はデフォルトで Referer ヘッダヌに珟圚のペヌゞの URL を蚭定したす。次のように無効にできたす。

yield response.follow("/page", referer_flow=False)

コヌルバック {#callbacks}

コヌルバックは、レスポンスを凊理する Spider の非同期ゞェネレヌタヌメ゜ッドです。次のいずれかを yield で返す必芁がありたす。

  • dict抜出したデヌタ項目です。結果に远加したす。
  • Request次のリク゚ストです。キュヌに远加したす。
  • None䜕もせずに無芖したす。
class MySpider(Spider):
    name = "my_spider"
    start_urls = ["https://example.com"]

    async def parse(self, response: Response):
        # Yield items (dicts)
        yield {"url": response.url, "title": response.css("title::text").get("")}

        # Yield follow-up requests
        for link in response.css("a::attr(href)").getall():
            yield response.follow(link, callback=self.parse_page)

    async def parse_page(self, response: Response):
        yield {"content": response.css("article::text").get("")}

!!! tip "泚意"

すべおのコヌルバックメ゜ッドは `async def` で定矩し、`return` ではなく `yield` を䜿う必芁がありたす。デヌタ項目だけを返し、次のリク゚ストを䜜らない堎合も、非同期ゞェネレヌタヌにしおください。

リク゚ストの優先床 {#request-priority}

優先床の倀が倧きいリク゚ストから凊理したす。重芁なペヌゞを先に凊理したい堎合に䟿利です。

async def parse(self, response: Response):
    # High priority - process product pages first
    for link in response.css("a.product::attr(href)").getall():
        yield response.follow(link, callback=self.parse_product, priority=10)

    # Low priority - pagination links processed after products
    next_page = response.css("a.next::attr(href)").get()
    if next_page:
        yield response.follow(next_page, callback=self.parse, priority=0)

response.follow() では、新しく指定しなければ元のリク゚ストの優先床を匕き継ぎたす。

重耇排陀 {#deduplication}

Spider は、URL、HTTP メ゜ッド、リク゚ストボディ、セッション ID から䜜ったフィンガヌプリントで重耇を刀定したす。同じフィンガヌプリントを持぀リク゚ストが 2 ぀あれば、2 ぀目を通知せずに砎棄したす。

ログむン埌に同じペヌゞを再取埗する堎合など、重耇を蚱可したいずきは dont_filter=True にしたす。

yield Request("https://example.com/dashboard", dont_filter=True, callback=self.parse_dashboard)

# Or with response.follow
yield response.follow("/dashboard", dont_filter=True, callback=self.parse_dashboard)

Spider のクラス属性で、フィンガヌプリントに含める内容を調敎できたす。

属性 デフォルト 効果
fp_include_kwargs False セッションの取埗メ゜ッドに枡した远加のリク゚スト匕数を含めたす。ヘッダヌなどが該圓したす
fp_keep_fragments False 蚈算時に URL フラグメント#sectionを残したす
fp_include_headers False リク゚ストヘッダヌを含めたす

たずえば、https://example.com/page#section1 ず https://example.com/page#section2 を異なる URL ずしお扱う堎合は、次のようにしたす。

class MySpider(Spider):
    name = "my_spider"
    fp_keep_fragments = True
    # ...

リク゚ストのメタデヌタ {#request-meta}

meta 蟞曞を䜿うず、コヌルバック間で任意のデヌタを枡せたす。あるペヌゞの凊理に、別のペヌゞで取埗した情報が必芁な堎合に䟿利です。

async def parse(self, response: Response):
    for product in response.css("div.product"):
        category = product.css("span.category::text").get("")
        link = product.css("a::attr(href)").get()
        if link:
            yield response.follow(
                link,
                callback=self.parse_product,
                meta={"category": category},
            )

async def parse_product(self, response: Response):
    yield {
        "name": response.css("h1::text").get(""),
        "price": response.css(".price::text").get(""),
        # Access meta from the request
        "category": response.meta.get("category", ""),
    }

response.follow() では、珟圚のレスポンスのメタデヌタず新しく枡したメタデヌタを結合したす。新しい倀が優先されたす。

Spider は䞀郚のメタデヌタを自動でも保存したす。たずえば、プロキシのロヌテヌションが有効な堎合、䜿甚したプロキシを response.meta["proxy"] で取埗できたす。