I have a spider that starts with a small list of allowed_domains
at the beginning of the spidering. I need to add more domains dynamically to this whitelist as
(At the very moment when this answer is written, the latest version of scrapy
is 1.0.3
. This answer shall work for all recent versions of scrapy
)
As the OffsiteMiddleware
reads the content in allowed_domains
only when initializing the precompiled regex object while handling the spider_opened
signal, values in allowed_domains
are never accessed later.
Thus simply updating the content of allowed_domains
shall not solve the problem.
Basically, two steps are required:
allowed_domains
according to your actual need.OffsiteMiddleware
refreshed.Here is the code I use for step #2:
# Refresh the regex cache for `allowed_domains`
for mw in self.crawler.engine.scraper.spidermw.middlewares:
if isinstance(mw, scrapy.spidermiddlewares.offsite.OffsiteMiddleware):
mw.spider_opened(self)
The code above is supposed to be invoked inside a response callback, thus self
here shall be an instance of the spider class.
See also: