ダウンローダーミドルウェア

ダウンローダーミドルウェアは, Scrapy のリクエスト/レスポンス処理へフックするフレームワークです. Scrapy のリクエストとレスポンスをグローバルに変更するための軽量で低レベルのシステムです.

ダウンローダーミドルウェアの有効化

ダウンローダーミドルウェアの有効化をするためには、DOWNLOADER_MIDDLEWARES に設定してください。 これは辞書であり、キーがミドルウェアクラスパスであり、値はミドルウェアのオーダーであることに注意してください。

例:

DOWNLOADER_MIDDLEWARES = {
    'myproject.middlewares.CustomDownloaderMiddleware': 543,
}

DOWNLOADER_MIDDLEWARES 設定はScrapy(オーバーリデンではない)で決められている :setting:`DOWNLOADER_MIDDLEWARES_BASE`とマージされます。その後、ソートされ実行される順番が決められます。 最初のミドルウェアがエンジンに近く、最後がダウンローダーに近いです。言い換えると、それぞれの:meth:`~scrapy.downloadermiddlewares.DownloaderMiddleware.process_request`メソッドが昇順で(100,200,300..)で実行されていき、それぞれの:meth:`~scrapy.downloadermiddlewares.DownloaderMiddleware.process_response`メソッドが降順で実行されます。

ミドルウェアの順番を決めるためには:setting:`DOWNLOADER_MIDDLEWARES_BASE`を参考にし、値を決める必要があります。順番はそれぞれのミドルウェアの関係性を考慮し決めなくてはなりません。

もしあなたが標準のミドルウェアを実行したくない場合は、DOWNLOADER_MIDDLEWARES`None`を設定してください。 例えばあなたがuser-agent middlewareを実行したくない場合は

DOWNLOADER_MIDDLEWARES = {
‘myproject.middlewares.CustomDownloaderMiddleware’: 543, ‘scrapy.downloadermiddlewares.useragent.UserAgentMiddleware’: None,

}

ミドルウェアの中には特別な設定が必要なものもあります。 詳しくはドキュメントを参照してください。

独自のダウンローダーミドルウェアの作成

各ミドルウェアコンポーネントは, 以下のメソッドの1つ以上を定義する Python クラスです:

class scrapy.downloadermiddlewares.DownloaderMiddleware

注釈

ダウンローダーミドルウェアメソッドのいずれも, 遅延したものを返す可能性があります.

process_request(request, spider)

This method is called for each request that goes through the download middleware.

process_request() should either: return None, return a Response object, return a Request object, or raise IgnoreRequest.

If it returns None, Scrapy will continue processing this request, executing all other middlewares until, finally, the appropriate downloader handler is called the request performed (and its response downloaded).

If it returns a Response object, Scrapy won’t bother calling any other process_request() or process_exception() methods, or the appropriate download function; it’ll return that response. The process_response() methods of installed middleware is always called on every response.

If it returns a Request object, Scrapy will stop calling process_request methods and reschedule the returned request. Once the newly returned request is performed, the appropriate middleware chain will be called on the downloaded response.

If it raises an IgnoreRequest exception, the process_exception() methods of installed downloader middleware will be called. If none of them handle the exception, the errback function of the request (Request.errback) is called. If no code handles the raised exception, it is ignored and not logged (unlike other exceptions).

パラメータ:
  • request (Request object) – the request being processed
  • spider (Spider object) – the spider for which this request is intended
process_response(request, response, spider)

process_response() should either: return a Response object, return a Request object or raise a IgnoreRequest exception.

If it returns a Response (it could be the same given response, or a brand-new one), that response will continue to be processed with the process_response() of the next middleware in the chain.

If it returns a Request object, the middleware chain is halted and the returned request is rescheduled to be downloaded in the future. This is the same behavior as if a request is returned from process_request().

If it raises an IgnoreRequest exception, the errback function of the request (Request.errback) is called. If no code handles the raised exception, it is ignored and not logged (unlike other exceptions).

パラメータ:
  • request (is a Request object) – the request that originated the response
  • response (Response object) – the response being processed
  • spider (Spider object) – the spider for which this response is intended
process_exception(request, exception, spider)

Scrapy calls process_exception() when a download handler or a process_request() (from a downloader middleware) raises an exception (including an IgnoreRequest exception)

process_exception() should return: either None, a Response object, or a Request object.

If it returns None, Scrapy will continue processing this exception, executing any other process_exception() methods of installed middleware, until no middleware is left and the default exception handling kicks in.

If it returns a Response object, the process_response() method chain of installed middleware is started, and Scrapy won’t bother calling any other process_exception() methods of middleware.

If it returns a Request object, the returned request is rescheduled to be downloaded in the future. This stops the execution of process_exception() methods of the middleware the same as returning a response would.

パラメータ:
  • request (is a Request object) – the request that generated the exception
  • exception (an Exception object) – the raised exception
  • spider (Spider object) – the spider for which this request is intended

ビルトインダウンローダーミドルウェアリファレンス

This page describes all downloader middleware components that come with Scrapy. For information on how to use them and how to write your own downloader middleware, see the downloader middleware usage guide.

デフォルトで有効になっているコンポーネントの一覧(およびそのオーダー)については, DOWNLOADER_MIDDLEWARES_BASE 設定を参照してください.

CookiesMiddleware

class scrapy.downloadermiddlewares.cookies.CookiesMiddleware

This middleware enables working with sites that require cookies, such as those that use sessions. It keeps track of cookies sent by web servers, and send them back on subsequent requests (from that spider), just like web browsers do.

The following settings can be used to configure the cookie middleware:

COOKIES_ENABLED

デフォルト: True

クッキーミドルウェアを有効にするかどうか. 無効にすると, Webサーバーにクッキーは送信されません.

COOKIES_DEBUG

デフォルト: False

If enabled, Scrapy will log all cookies sent in requests (ie. Cookie header) and all cookies received in responses (ie. Set-Cookie header).

Here’s an example of a log with COOKIES_DEBUG enabled:

2011-04-06 14:35:10-0300 [scrapy] INFO: Spider opened
2011-04-06 14:35:10-0300 [scrapy] DEBUG: Sending cookies to: <GET http://www.diningcity.com/netherlands/index.html>
        Cookie: clientlanguage_nl=en_EN
2011-04-06 14:35:14-0300 [scrapy] DEBUG: Received cookies from: <200 http://www.diningcity.com/netherlands/index.html>
        Set-Cookie: JSESSIONID=B~FA4DC0C496C8762AE4F1A620EAB34F38; Path=/
        Set-Cookie: ip_isocode=US
        Set-Cookie: clientlanguage_nl=en_EN; Expires=Thu, 07-Apr-2011 21:21:34 GMT; Path=/
2011-04-06 14:49:50-0300 [scrapy] DEBUG: Crawled (200) <GET http://www.diningcity.com/netherlands/index.html> (referer: None)
[...]

DefaultHeadersMiddleware

class scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware

This middleware sets all default requests headers specified in the DEFAULT_REQUEST_HEADERS setting.

DownloadTimeoutMiddleware

class scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware

This middleware sets the download timeout for requests specified in the DOWNLOAD_TIMEOUT setting or download_timeout spider attribute.

注釈

You can also set download timeout per-request using download_timeout Request.meta key; this is supported even when DownloadTimeoutMiddleware is disabled.

HttpAuthMiddleware

class scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware

このミドルウェアは, Basic access authentication (別名HTTP認証)を使用して, 特定のスパイダーから生成されたすべてのリクエストを認証します.

特定のスパイダーからHTTP認証を有効にするには, これらのスパイダーの http_user および http_pass 属性を設定します.

例:

from scrapy.spiders import CrawlSpider

class SomeIntranetSiteSpider(CrawlSpider):

    http_user = 'someuser'
    http_pass = 'somepass'
    name = 'intranet.example.com'

    # .. 残りのスパイダーコードは省略されています ...

HttpCacheMiddleware

class scrapy.downloadermiddlewares.httpcache.HttpCacheMiddleware

このミドルウェアは, すべてのHTTPリクエストとレスポンスに低レベルのキャッシュを提供します. これはキャッシュストレージバックエンドとキャッシュポリシーとを組み合わせなければなりません.

2つのHTTPキャッシュストレージバックエンドを持つ Scrapy:

HTTPキャッシュストレージバックエンドは, HTTPCACHE_STORAGE 設定で変更できます. また, 独自のストレージバックエンドを実装することもできます.

2つのHTTPキャッシュポリシーを持つ Scrapy:

HTTPCACHE_POLICY 設定を使用してHTTPキャッシュポリシーを変更できます. あるいは独自のポリシーを実装することもできます.

また, dont_cache メタキーを True とすると, すべてのポリシーで応答をキャッシュすることを避けることができます.

ダミーポリシー (デフォルト)

このポリシーは, HTTP Cache-Control ディレクティブを意識していません. すべてのリクエストとそれに対応するレスポンスがキャッシュされます. 同じリクエストが再び見られると, インターネットから何も転送せずにレスポンスが返されます.

ダミーポリシーは, スパイダーを素早くテストする(毎回ダウンロードを待たずに), または, インターネット接続が利用できないときにスパイダーをオフラインで試すのに便利です. 目標は, 以前に実行されたとおりにスパイダーの実行を「再生」できるようにすることです.

このポリシーを使用するには:

  • HTTPCACHE_POLICY に scrapy.extensions.httpcache.DummyPolicy を設定します.

RFC2616 ポリシー

このポリシーは, HTTPキャッシュ制御の認識を備えた RFC2616 準拠の HTTP キャッシュを提供し, 生産を目的とし, 変更なしのデータのダウンロードを避けるために連続実行で 使用します(帯域幅を節約し, クロールを高速化します).

実装されているもの:

  • no-store キャッシュ制御ディレクティブセットで, レスポンス/リクエストを格納しない

  • 新しいレスポンスに対しても no-cache キャッシュコントロール指令が設定されている場合, キャッシュからの応答を提供しない

  • max-age キャッシュ制御命令からフレッシュネスライフタイムを計算する

  • Expires レスポンスヘッダーからフレッシュネスライフタイムを計算する

  • Last-Modified レスポンスヘッダ(Firefoxで使用されるヒューリスティック)からフレッシュネスライフタイムを計算

  • Age レスポンスヘッダから現在の年齢を計算する

  • Date ヘッダから現在の年齢を計算する

  • Last-Modified レスポンスヘッダに基づいて失効したレスポンスを再確認する

  • ETag レスポンスヘッダーにもとづいて失効した応答を再検証する

  • 受け取らなかったレスポンスの Date` ヘッダーを設定しない

  • リクエストにおける max-stale キャッシュ制御命令をサポート

    これにより, スパイダーを完全なRFC2616キャッシュポリシーで構成することができますが, HTTP仕様に準拠したままで, リクエストごとに再検証は行われません.

    例:

    Cache-Control: max-stale=600 を追加して, 有効期限を超過したリクエストを600秒以下で受け入れるようにヘッダーに要求します.

    参照: RFC2616, 14.9.3

何が無くなったか:

このポリシーを使用するには:

  • HTTPCACHE_POLICY に scrapy.extensions.httpcache.RFC2616Policy を設定します.

ファイルシステムストレージバックエンド (デフォルト)

ファイルシステムストレージバックエンドは, HTTPキャッシュミドルウェアで使用できます.

このストレージバックエンドを使用するには:

  • HTTPCACHE_STORAGEscrapy.extensions.httpcache.FilesystemCacheStorage を設定します.

各 request/response のペアは, 次のファイルを含む別のディレクトリに格納されます:

  • request_body - the plain request body
  • request_headers - the request headers (in raw HTTP format)
  • response_body - the plain response body
  • response_headers - the request headers (in raw HTTP format)
  • meta - some metadata of this cache resource in Python repr() format (grep-friendly format)
  • pickled_meta - the same metadata in meta but pickled for more efficient deserialization

ディレクトリ名はリクエストフィンガープリント ( scrapy.utils.request.fingerprint を参照)から作成され, 1つのレベルのサブディレクトリが, 同じディレクトリにあまりにも多くのファイルを作成することを 避けるために使用されます(多くのファイルシステムでは非効率的です):

/path/to/cache/dir/example.com/72/72811f648e718090f041317756c03adb0ada46c7

DBM ストレージバックエンド

バージョン 0.13 で追加.

DBM ストレージバックエンドは, HTTPキャッシュミドルウェアでも使用できます.

デフォルトでは, anydbm モジュールを使用しますが, HTTPCACHE_DBM_MODULE 設定で変更することができます.

このストレージバックエンドを使用するには:

  • HTTPCACHE_STORAGEscrapy.extensions.httpcache.DbmCacheStorage を設定します.

LevelDB ストレージバックエンド

バージョン 0.23 で追加.

LevelDB ストレージバックエンドは, HTTPキャッシュミドルウェアでも使用できます.

このバックエンドは開発プロセスにはお勧めできません. これは, 同時に1つのプロセスしか LevelDB データベースにアクセスできないためです. そのため, 同じスパイダーに対して並列に Scrapy シェルを開くことはできません.

このストレージバックエンドを使用するには:

HTTPCache middleware 設定

HttpCacheMiddleware は, 次の設定で構成されています:

HTTPCACHE_ENABLED

バージョン 0.11 で追加.

デフォルト: False

HTTPキャッシュを有効にするかどうか.

バージョン 0.11 で変更: 0.11 より前では, キャッシュを有効にするために HTTPCACHE_DIR が使用されていました.

HTTPCACHE_EXPIRATION_SECS

デフォルト: 0

キャッシュされたリクエストの有効期限(秒単位).

この時間より古いキャッシュされたリクエストは再ダウンロードされます. 0の場合, キャッシュされたリクエストは期限切れになりません.

バージョン 0.11 で変更: 0.11 以前は, 0 はキャッシュされたリクエストが常に期限切れになることを意味しました.

HTTPCACHE_DIR

デフォルト: 'httpcache'

(低レベル)HTTPキャッシュを格納するために使用するディレクトリ. 空の場合, HTTPキャッシュは無効になります. 相対パスが指定されている場合は, プロジェクトデータディレクトリに対して相対パスが使用されます. 詳細は, Scrapyプロジェクトのデフォルト構造 を参照してください.

HTTPCACHE_IGNORE_HTTP_CODES

バージョン 0.10 で追加.

デフォルト: []

キャッシュしないレスポンスの HTTP コード.

HTTPCACHE_IGNORE_MISSING

デフォルト: False

有効にすると, キャッシュにないリクエストはダウンロードされずに無視されます.

HTTPCACHE_IGNORE_SCHEMES

バージョン 0.10 で追加.

デフォルト: ['file']

キャッシュしないレスポンスのURIスキーム.

HTTPCACHE_STORAGE

デフォルト: 'scrapy.extensions.httpcache.FilesystemCacheStorage'

キャッシュストレージバックエンドを実装するクラス.

HTTPCACHE_DBM_MODULE

バージョン 0.13 で追加.

デフォルト: 'anydbm'

DBMストレージバックエンド で使用するデータベースモジュール. この設定は, DBMバックエンド特有です.

HTTPCACHE_POLICY

バージョン 0.18 で追加.

デフォルト: 'scrapy.extensions.httpcache.DummyPolicy'

キャッシュポリシーを実装するクラス.

HTTPCACHE_GZIP

バージョン 1.0 で追加.

デフォルト: False

有効にすると, キャッシュされたすべてのデータがgzipで圧縮されます. この設定はファイルシステムのバックエンド特有です.

HTTPCACHE_ALWAYS_STORE

バージョン 1.1 で追加.

デフォルト: False

有効にすると, 無条件にページをキャッシュします.

スパイダーは, Cache-Control: max-stale などを将来使用するために, すべてのレスポンスをキャッシュで利用できるようにすることができます. DummyPolicy はすべてのレスポンスをキャッシュしますが, それを再検証することはありません. また, 別のポリシーが望ましい場合もあります.

この設定は, 依然として Cache-Control: no-store ディレクティブを尊重します. 必要がない場合は, キャッシュミドルウェアにフィードしたレスポンスの Cache-Control ヘッダーから no-store を除外します.

HTTPCACHE_IGNORE_RESPONSE_CACHE_CONTROLS

バージョン 1.1 で追加.

デフォルト: []

無視されるレスポンスのキャッシュ制御ディレクティブのリスト.

サイトはしばしば “no-store”, “no-cache”, “must-revalidate”, などを設定しますが, スパイダーがそれらのディレクティブを尊重するならば生成できるトラフィックで動揺します. これにより, クロールしているサイトの重要でないことがわかっている Cache-Control ディレクティブを選択的に無視することができます.

スパイダーは実際に Cache-Control ディレクティブを必要としない限り, Cache-Control ディレクティブを発行しないので, リクエスト内のディレクティブはフィルタリングされません.

HttpCompressionMiddleware

class scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware

このミドルウェアは, 圧縮された(gzip, deflate)トラフィックをWebサイトから送受信できるようにします.

HttpCompressionMiddleware 設定

COMPRESSION_ENABLED

デフォルト: True

HttpCompressionMiddleware を有効にするかどうか.

HttpProxyMiddleware

バージョン 0.8 で追加.

class scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware

This middleware sets the HTTP proxy to use for requests, by setting the proxy meta value for Request objects.

Like the Python standard library modules urllib and urllib2, it obeys the following environment variables:

  • http_proxy
  • https_proxy
  • no_proxy

You can also set the meta key proxy per-request, to a value like http://some_proxy_server:port.

RedirectMiddleware

class scrapy.downloadermiddlewares.redirect.RedirectMiddleware

このミドルウェアは, 応答ステータスに基づいてリクエストのリダイレクトを処理します.

The urls which the request goes through (while being redirected) can be found in the redirect_urls Request.meta key.

The RedirectMiddleware can be configured through the following settings (see the settings documentation for more info):

If Request.meta has dont_redirect key set to True, the request will be ignored by this middleware.

If you want to handle some redirect status codes in your spider, you can specify these in the handle_httpstatus_list spider attribute.

For example, if you want the redirect middleware to ignore 301 and 302 responses (and pass them through to your spider) you can do this:

class MySpider(CrawlSpider):
    handle_httpstatus_list = [301, 302]

The handle_httpstatus_list key of Request.meta can also be used to specify which response codes to allow on a per-request basis. You can also set the meta key handle_httpstatus_all to True if you want to allow any response code for a request.

RedirectMiddleware 設定

REDIRECT_ENABLED

バージョン 0.13 で追加.

デフォルト: True

RedirectMiddleware を有効にするかどうか.

REDIRECT_MAX_TIMES

デフォルト: 20

1回のリクエストで実行されるリダイレクトの最大数.

MetaRefreshMiddleware

class scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware

このミドルウェアは, メタリフレッシュhtmlタグに基づいてリクエストのリダイレクトを処理します.

The MetaRefreshMiddleware can be configured through the following settings (see the settings documentation for more info):

This middleware obey REDIRECT_MAX_TIMES setting, dont_redirect and redirect_urls request meta keys as described for RedirectMiddleware

MetaRefreshMiddleware 設定

METAREFRESH_ENABLED

バージョン 0.17 で追加.

デフォルト: True

MetaRefreshMiddleware を有効にするかどうか.

METAREFRESH_MAXDELAY

デフォルト: 100

The maximum meta-refresh delay (in seconds) to follow the redirection. Some sites use meta-refresh for redirecting to a session expired page, so we restrict automatic redirection to the maximum delay.

RetryMiddleware

class scrapy.downloadermiddlewares.retry.RetryMiddleware

A middleware to retry failed requests that are potentially caused by temporary problems such as a connection timeout or HTTP 500 error.

Failed pages are collected on the scraping process and rescheduled at the end, once the spider has finished crawling all regular (non failed) pages. Once there are no more failed pages to retry, this middleware sends a signal (retry_complete), so other extensions could connect to that signal.

The RetryMiddleware can be configured through the following settings (see the settings documentation for more info):

If Request.meta has dont_retry key set to True, the request will be ignored by this middleware.

RetryMiddleware 設定

RETRY_ENABLED

バージョン 0.13 で追加.

デフォルト: True

RetryMiddleware を有効にするかどうか.

RETRY_TIMES

デフォルト: 2

最初のダウンロードに加えて, 再試行の最大回数.

RETRY_HTTP_CODES

デフォルト: [500, 502, 503, 504, 408]

Which HTTP response codes to retry. Other errors (DNS lookup issues, connections lost, etc) are always retried.

In some cases you may want to add 400 to RETRY_HTTP_CODES because it is a common code used to indicate server overload. It is not included by default because HTTP specs say so.

RobotsTxtMiddleware

class scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware

This middleware filters out requests forbidden by the robots.txt exclusion standard.

To make sure Scrapy respects robots.txt make sure the middleware is enabled and the ROBOTSTXT_OBEY setting is enabled.

If Request.meta has dont_obey_robotstxt key set to True the request will be ignored by this middleware even if ROBOTSTXT_OBEY is enabled.

DownloaderStats

class scrapy.downloadermiddlewares.stats.DownloaderStats

Middleware that stores stats of all requests, responses and exceptions that pass through it.

To use this middleware you must enable the DOWNLOADER_STATS setting.

UserAgentMiddleware

class scrapy.downloadermiddlewares.useragent.UserAgentMiddleware

スパイダーがデフォルトのユーザーエージェントをオーバーライドできるミドルウェア.

In order for a spider to override the default user agent, its user_agent attribute must be set.

AjaxCrawlMiddleware

class scrapy.downloadermiddlewares.ajaxcrawl.AjaxCrawlMiddleware

Middleware that finds ‘AJAX crawlable’ page variants based on meta-fragment html tag. See https://developers.google.com/webmasters/ajax-crawling/docs/getting-started for more info.

注釈

Scrapy finds ‘AJAX crawlable’ pages for URLs like 'http://example.com/!#foo=bar' even without this middleware. AjaxCrawlMiddleware is necessary when URL doesn’t contain '!#'. This is often a case for ‘index’ or ‘main’ website pages.

AjaxCrawlMiddleware 設定

AJAXCRAWL_ENABLED

バージョン 0.21 で追加.

デフォルト: False

Whether the AjaxCrawlMiddleware will be enabled. You may want to enable it for broad crawls.

HttpProxyMiddleware 設定

HTTPPROXY_AUTH_ENCODING

デフォルト: "latin-1"

The default encoding for proxy authentication on HttpProxyMiddleware.