ダウンローダーミドルウェア¶
ダウンローダーミドルウェアは, 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: returnNone
, return aResponse
object, return aRequest
object, or raiseIgnoreRequest
.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 otherprocess_request()
orprocess_exception()
methods, or the appropriate download function; it’ll return that response. Theprocess_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, theprocess_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).パラメータ:
-
process_response
(request, response, spider)¶ process_response()
should either: return aResponse
object, return aRequest
object or raise aIgnoreRequest
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 theprocess_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 fromprocess_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).パラメータ:
-
process_exception
(request, exception, spider)¶ Scrapy calls
process_exception()
when a download handler or aprocess_request()
(from a downloader middleware) raises an exception (including anIgnoreRequest
exception)process_exception()
should return: eitherNone
, aResponse
object, or aRequest
object.If it returns
None
, Scrapy will continue processing this exception, executing any otherprocess_exception()
methods of installed middleware, until no middleware is left and the default exception handling kicks in.If it returns a
Response
object, theprocess_response()
method chain of installed middleware is started, and Scrapy won’t bother calling any otherprocess_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 ofprocess_exception()
methods of the middleware the same as returning a response would.パラメータ:
-
ビルトインダウンローダーミドルウェアリファレンス¶
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¶
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:
スパイダーごとに複数のCookieセッション¶
バージョン 0.15 で追加.
There is support for keeping multiple cookie sessions per spider by using the
cookiejar
Request meta key. By default it uses a single cookie jar
(session), but you can pass an identifier to use different ones.
たとえば:
for i, url in enumerate(urls):
yield scrapy.Request(url, meta={'cookiejar': i},
callback=self.parse_page)
Keep in mind that the cookiejar
meta key is not “sticky”. You need to keep
passing it along on subsequent requests. For example:
def parse_page(self, response):
# do some processing
return scrapy.Request("http://www.example.com/otherpage",
meta={'cookiejar': response.meta['cookiejar']},
callback=self.parse_other_page)
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 ordownload_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
何が無くなったか:
- Pragma: no-cache サポート https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.1
- Vary ヘッダーサポート https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.6
- 更新または削除後の無効化 https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.10
- ... おそらく他にも ..
このポリシーを使用するには:
HTTPCACHE_POLICY
にscrapy.extensions.httpcache.RFC2616Policy
を設定します.
ファイルシステムストレージバックエンド (デフォルト)¶
ファイルシステムストレージバックエンドは, HTTPキャッシュミドルウェアで使用できます.
このストレージバックエンドを使用するには:
HTTPCACHE_STORAGE
にscrapy.extensions.httpcache.FilesystemCacheStorage
を設定します.
各 request/response のペアは, 次のファイルを含む別のディレクトリに格納されます:
request_body
- the plain request bodyrequest_headers
- the request headers (in raw HTTP format)response_body
- the plain response bodyresponse_headers
- the request headers (in raw HTTP format)meta
- some metadata of this cache resource in Pythonrepr()
format (grep-friendly format)pickled_meta
- the same metadata inmeta
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_STORAGE
にscrapy.extensions.httpcache.DbmCacheStorage
を設定します.
LevelDB ストレージバックエンド¶
バージョン 0.23 で追加.
LevelDB ストレージバックエンドは, HTTPキャッシュミドルウェアでも使用できます.
このバックエンドは開発プロセスにはお勧めできません. これは, 同時に1つのプロセスしか LevelDB データベースにアクセスできないためです. そのため, 同じスパイダーに対して並列に Scrapy シェルを開くことはできません.
このストレージバックエンドを使用するには:
HTTPCACHE_STORAGE
にscrapy.extensions.httpcache.LeveldbCacheStorage
を設定しますpip install leveldb
のようにして, LevelDB の Python バインディング をインストールします
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_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サイトから送受信できるようにします.
HttpProxyMiddleware¶
バージョン 0.8 で追加.
-
class
scrapy.downloadermiddlewares.httpproxy.
HttpProxyMiddleware
¶ This middleware sets the HTTP proxy to use for requests, by setting the
proxy
meta value forRequest
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 likehttp://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.
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
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_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.