コア API

バージョン 0.15 で追加.

このセクションは, ScrapyコアAPIについて説明します. 拡張APIやミドルウェアの開発者向けです.

クローラー API

Scrapy API の主なエントリポイントは, from_crawler メソッドを使用して拡張機能に渡される Crawler オブジェクトです. このオブジェクトはすべての Scrapy コアコンポーネントへのアクセスを提供し, 拡張機能がそれらにアクセスして機能を Scrapy に引き込む唯一の方法です.

拡張機能マネージャーは, インストールされている拡張機能の読み込みと追跡を担当しており, 使用可能なすべての拡張機能の辞書と, ダウンローダーミドルウェアの設定 方法と同様の命令を含む EXTENSIONS 設定によって構成されています.

class scrapy.crawler.Crawler(spidercls, settings)

Crawler オブジェクトは, scrapy.spiders.Spider サブクラスと scrapy.settings.Settings オブジェクトでインスタンス化する必要があります.

settings

クローラの設定マネージャ.

これは, このクローラーのScrapy設定にアクセスするために拡張機能とミドルウェアによって使用されます.

詳細については,  設定 を参照してください.

APIについては, Settings クラスを参照してください.

signals

クローラーの信号マネージャ.

これは, 拡張機能とミドルウェアがScrapy機能にフックするために使用されます.

詳細については, シグナル を参照してください.

APIについては, SignalManager クラスを参照してください.

stats

クローラーの統計コレクタ.

これは, エクステンションとミドルウェアから自分の行動の統計情報を記録したり, 他の拡張機能によって収集された統計情報にアクセスするために使用されます.

詳細については 統計コレクション を参照してください.

API については StatsCollector クラスを参照してください.

extensions

有効な拡張機能を追跡する拡張マネージャー.

ほとんどの拡張機能はこの属性にアクセスする必要はありません.

拡張機能の紹介とScrapyの利用可能な拡張機能のリストについては, 拡張機能 を参照してください.

engine

実行エンジン. スケジューラ, ダウンローダ, およびスパイダ間のコアクロールロジックを調整します.

Scrapy エンジンにアクセスして, ダウンローダとスケジューラの動作を検査または変更したい場合にしようできます. ただし, これは高度な使い方であり, APIはまだ安定していません.

spider

Spider currently being crawled. クローラの構築中に提供されるspiderクラスのインスタンスであり, crawl() メソッドで指定された引数の後に作成されます.

crawl(*args, **kwargs)

クローラー開始時に, 指定された args および kwargs 引数を使用してスパイダーをインスタンス化し, 実行エンジンの動作を設定します.

クロールが終了したときに発生する遅延を返します.

class scrapy.crawler.CrawlerRunner(settings=None)

This is a convenient helper class that keeps track of, manages and runs crawlers inside an already setup Twisted reactor.

The CrawlerRunner object must be instantiated with a Settings object.

This class shouldn’t be needed (since Scrapy is responsible of using it accordingly) unless writing scripts that manually handle the crawling process. See スクリプトから Scrapy を実行する for an example.

crawl(crawler_or_spidercls, *args, **kwargs)

Run a crawler with the provided arguments.

It will call the given Crawler’s crawl() method, while keeping track of it so it can be stopped later.

If crawler_or_spidercls isn’t a Crawler instance, this method will try to create one using this parameter as the spider class given to it.

Returns a deferred that is fired when the crawling is finished.

パラメータ:
  • crawler_or_spidercls (Crawler instance, Spider subclass or string) – already created crawler, or a spider class or spider’s name inside the project to create it
  • args (list) – arguments to initialize the spider
  • kwargs (dict) – keyword arguments to initialize the spider
crawlers

Set of crawlers started by crawl() and managed by this class.

create_crawler(crawler_or_spidercls)

Return a Crawler object.

  • If crawler_or_spidercls is a Crawler, it is returned as-is.
  • If crawler_or_spidercls is a Spider subclass, a new Crawler is constructed for it.
  • If crawler_or_spidercls is a string, this function finds a spider with this name in a Scrapy project (using spider loader), then creates a Crawler instance for it.
join()

Returns a deferred that is fired when all managed crawlers have completed their executions.

stop()

Stops simultaneously all the crawling jobs taking place.

Returns a deferred that is fired when they all have ended.

class scrapy.crawler.CrawlerProcess(settings=None)

ベースクラス: scrapy.crawler.CrawlerRunner

A class to run multiple scrapy crawlers in a process simultaneously.

This class extends CrawlerRunner by adding support for starting a Twisted reactor and handling shutdown signals, like the keyboard interrupt command Ctrl-C. It also configures top-level logging.

This utility should be a better fit than CrawlerRunner if you aren’t running another Twisted reactor within your application.

The CrawlerProcess object must be instantiated with a Settings object.

This class shouldn’t be needed (since Scrapy is responsible of using it accordingly) unless writing scripts that manually handle the crawling process. See スクリプトから Scrapy を実行する for an example.

crawl(crawler_or_spidercls, *args, **kwargs)

Run a crawler with the provided arguments.

It will call the given Crawler’s crawl() method, while keeping track of it so it can be stopped later.

If crawler_or_spidercls isn’t a Crawler instance, this method will try to create one using this parameter as the spider class given to it.

Returns a deferred that is fired when the crawling is finished.

パラメータ:
  • crawler_or_spidercls (Crawler instance, Spider subclass or string) – already created crawler, or a spider class or spider’s name inside the project to create it
  • args (list) – arguments to initialize the spider
  • kwargs (dict) – keyword arguments to initialize the spider
crawlers

Set of crawlers started by crawl() and managed by this class.

create_crawler(crawler_or_spidercls)

Return a Crawler object.

  • If crawler_or_spidercls is a Crawler, it is returned as-is.
  • If crawler_or_spidercls is a Spider subclass, a new Crawler is constructed for it.
  • If crawler_or_spidercls is a string, this function finds a spider with this name in a Scrapy project (using spider loader), then creates a Crawler instance for it.
join()

Returns a deferred that is fired when all managed crawlers have completed their executions.

start(stop_after_crawl=True)

This method starts a Twisted reactor, adjusts its pool size to REACTOR_THREADPOOL_MAXSIZE, and installs a DNS cache based on DNSCACHE_ENABLED and DNSCACHE_SIZE.

If stop_after_crawl is True, the reactor will be stopped after all crawlers have finished, using join().

パラメータ:stop_after_crawl (boolean) – stop or not the reactor when all crawlers have finished
stop()

Stops simultaneously all the crawling jobs taking place.

Returns a deferred that is fired when they all have ended.

設定 API

scrapy.settings.SETTINGS_PRIORITIES

Scrapyで使用されるデフォルトの設定優先度のキー名と優先度を辞書形式で設定します.

各項目は設定エントリポイントを定義し, 識別のためのコード名と整数の優先順位を与えます. Settings クラスで値を設定したり取得したりするときは, 優先度が高いほど優先度が低くなります.

SETTINGS_PRIORITIES = {
    'default': 0,
    'command': 10,
    'project': 20,
    'spider': 30,
    'cmdline': 40,
}

各設定の詳細については, 設定 を参照してください.

scrapy.settings.get_settings_priority(priority)

Small helper function that looks up a given string priority in the SETTINGS_PRIORITIES dictionary and returns its numerical value, or directly returns a given numerical priority.

class scrapy.settings.Settings(values=None, priority='project')

ベースクラス: scrapy.settings.BaseSettings

This object stores Scrapy settings for the configuration of internal components, and can be used for any further customization.

It is a direct subclass and supports all methods of BaseSettings. Additionally, after instantiation of this class, the new object will have the global default settings described on ビルトイン設定リファレンス already populated.

class scrapy.settings.BaseSettings(values=None, priority='project')

Instances of this class behave like dictionaries, but store priorities along with their (key, value) pairs, and can be frozen (i.e. marked immutable).

Key-value entries can be passed on initialization with the values argument, and they would take the priority level (unless values is already an instance of BaseSettings, in which case the existing priority levels will be kept). If the priority argument is a string, the priority name will be looked up in SETTINGS_PRIORITIES. Otherwise, a specific integer should be provided.

Once the object is created, new settings can be loaded or updated with the set() method, and can be accessed with the square bracket notation of dictionaries, or with the get() method of the instance and its value conversion variants. When requesting a stored key, the value with the highest priority will be retrieved.

copy()

Make a deep copy of current settings.

This method returns a new instance of the Settings class, populated with the same values and their priorities.

Modifications to the new object won’t be reflected on the original settings.

copy_to_dict()

Make a copy of current settings and convert to a dict.

This method returns a new dict populated with the same values and their priorities as the current settings.

Modifications to the returned dict won’t be reflected on the original settings.

This method can be useful for example for printing settings in Scrapy shell.

freeze()

Disable further changes to the current settings.

After calling this method, the present state of the settings will become immutable. Trying to change values through the set() method and its variants won’t be possible and will be alerted.

frozencopy()

Return an immutable copy of the current settings.

Alias for a freeze() call in the object returned by copy().

get(name, default=None)

Get a setting value without affecting its original type.

パラメータ:
  • name (string) – the setting name
  • default (any) – the value to return if no setting is found
getbool(name, default=False)

Get a setting value as a boolean.

1, '1', and True return True, while 0, '0', False and None return False.

For example, settings populated through environment variables set to '0' will return False when using this method.

パラメータ:
  • name (string) – the setting name
  • default (any) – the value to return if no setting is found
getdict(name, default=None)

Get a setting value as a dictionary. If the setting original type is a dictionary, a copy of it will be returned. If it is a string it will be evaluated as a JSON dictionary. In the case that it is a BaseSettings instance itself, it will be converted to a dictionary, containing all its current settings values as they would be returned by get(), and losing all information about priority and mutability.

パラメータ:
  • name (string) – the setting name
  • default (any) – the value to return if no setting is found
getfloat(name, default=0.0)

Get a setting value as a float.

パラメータ:
  • name (string) – the setting name
  • default (any) – the value to return if no setting is found
getint(name, default=0)

Get a setting value as an int.

パラメータ:
  • name (string) – the setting name
  • default (any) – the value to return if no setting is found
getlist(name, default=None)

Get a setting value as a list. If the setting original type is a list, a copy of it will be returned. If it’s a string it will be split by ”,”.

For example, settings populated through environment variables set to 'one,two' will return a list [‘one’, ‘two’] when using this method.

パラメータ:
  • name (string) – the setting name
  • default (any) – the value to return if no setting is found
getpriority(name)

Return the current numerical priority value of a setting, or None if the given name does not exist.

パラメータ:name (string) – the setting name
getwithbase(name)

Get a composition of a dictionary-like setting and its _BASE counterpart.

パラメータ:name (string) – name of the dictionary-like setting
maxpriority()

Return the numerical value of the highest priority present throughout all settings, or the numerical value for default from SETTINGS_PRIORITIES if there are no settings stored.

set(name, value, priority='project')

Store a key/value attribute with a given priority.

Settings should be populated before configuring the Crawler object (through the configure() method), otherwise they won’t have any effect.

パラメータ:
  • name (string) – the setting name
  • value (any) – the value to associate with the setting
  • priority (string or int) – the priority of the setting. Should be a key of SETTINGS_PRIORITIES or an integer
setmodule(module, priority='project')

Store settings from a module with a given priority.

This is a helper function that calls set() for every globally declared uppercase variable of module with the provided priority.

パラメータ:
  • module (module object or string) – the module or the path of the module
  • priority (string or int) – the priority of the settings. Should be a key of SETTINGS_PRIORITIES or an integer
update(values, priority='project')

Store key/value pairs with a given priority.

This is a helper function that calls set() for every item of values with the provided priority.

If values is a string, it is assumed to be JSON-encoded and parsed into a dict with json.loads() first. If it is a BaseSettings instance, the per-key priorities will be used and the priority parameter ignored. This allows inserting/updating settings with different priorities with a single command.

パラメータ:
  • values (dict or string or BaseSettings) – the settings names and values
  • priority (string or int) – the priority of the settings. Should be a key of SETTINGS_PRIORITIES or an integer

スパイダーローダー API

class scrapy.loader.SpiderLoader

このクラスは, プロジェクト全体で定義されたスパイダークラスの取得と処理を担当します.

SPIDER_LOADER_CLASS プロジェクト設定でパスを指定することで, カスタムスパイダーローダーを使用できます. エラーのない実行を保証するために scrapy.interfaces.ISpiderLoader インタフェースを完全に実装する必要があります.

from_settings(settings)

このクラスメソッドは, クラスのインスタンスを作成するためにScrapyによって使用されます. プロジェクト設定で呼び出され,  SPIDER_MODULES 設定で指定したモジュール内で再帰的に見つかったスパイダーをロードします.

パラメータ:settings (Settings インスタンス) – プロジェクト設定
load(spider_name)

Spider クラスを指定された名前で取得します. 以前に読み込まれたスパイダーのうち, spider_name という名前の Spider クラスが検索され, 見つからなければ KeyError が発生します.

パラメータ:spider_name (str) – Spider クラス名
list()

プロジェクトで利用可能なスパイダーの名前を取得する.

find_by_request(request)

指定されたリクエストを処理できるスパイダーの名前をリストします. 要求のURLとスパイダーのドメインを照合しようとします.

パラメータ:request (Request インスタンス) – 問い合わされたリクエスト

シグナル API

class scrapy.signalmanager.SignalManager(sender=_Anonymous)
connect(receiver, signal, **kwargs)

Connect a receiver function to a signal.

The signal can be any object, although Scrapy comes with some predefined signals that are documented in the シグナル section.

パラメータ:
  • receiver (callable) – the function to be connected
  • signal (object) – the signal to connect to
disconnect(receiver, signal, **kwargs)

Disconnect a receiver function from a signal. This has the opposite effect of the connect() method, and the arguments are the same.

disconnect_all(signal, **kwargs)

Disconnect all receivers from the given signal.

パラメータ:signal (object) – the signal to disconnect from
send_catch_log(signal, **kwargs)

Send a signal, catch exceptions and log them.

The keyword arguments are passed to the signal handlers (connected through the connect() method).

send_catch_log_deferred(signal, **kwargs)

Like send_catch_log() but supports returning deferreds from signal handlers.

Returns a Deferred that gets fired once all signal handlers deferreds were fired. Send a signal, catch exceptions and log them.

The keyword arguments are passed to the signal handlers (connected through the connect() method).

統計コレクター API

scrapy.statscollectors モジュールの下に利用可能ないくつかの統計コレクタがあり, それらはすべて StatsCollector クラスで定義されたStatsコレクタAPIを実装しています(すべて継承しています).

class scrapy.statscollectors.StatsCollector
get_value(key, default=None)

指定されたstatsキーの値を返します. 存在しない場合はdefaultを返します.

get_stats()

現在実行中のスパイダーからすべての統計情報を dict として取得します.

set_value(key, value)

与えられた stats キーに与えられた値を設定します.

set_stats(stats)

stats 引数に渡された dict で現在の統計をオーバーライドします.

inc_value(key, count=1, start=0)

指定された統計値キーの値を与えられた数だけ増やします(設定されていない場合は, 与えられた開始値を仮定する).

max_value(key, value)

指定されたキーの現在の値が value よりも小さい場合にのみ, 指定されたキーの値に value を設定します. 指定されたキーに現在の値がない場合, 値は常に設定されます.

min_value(key, value)

指定されたキーの現在の値が value より大きい場合にのみ, 指定されたキーの値に value を設定します. 指定されたキーに現在の値がない場合, 値は常に設定されます.

clear_stats()

すべての統計情報をクリアします.

次のメソッドは, 統計収集APIの一部ではなく, カスタム統計コレクタを実装するときに使用されます:

open_spider(spider)

統計収集のために指定されたスパイダーを開きます.

close_spider(spider)

指定されたスパイダーを閉じます. これが呼び出された後, 特定の統計情報にアクセスまたは収集することはできません.