Я строю рекурсивный webspider с дополнительным логином. Я хочу сделать большинство настроек динамическими с помощью json-файла конфигурации.scrapy InitSpider: установить правила в __init__?
В моей функции __init__
, я читаю этот файл и пытаюсь заполнить все переменные, однако это не работает с Rules
.
class CrawlpySpider(InitSpider):
...
#----------------------------------------------------------------------
def __init__(self, *args, **kwargs):
"""Constructor: overwrite parent __init__ function"""
# Call parent init
super(CrawlpySpider, self).__init__(*args, **kwargs)
# Get command line arg provided configuration param
config_file = kwargs.get('config')
# Validate configuration file parameter
if not config_file:
logging.error('Missing argument "-a config"')
logging.error('Usage: scrapy crawl crawlpy -a config=/path/to/config.json')
self.abort = True
# Check if it is actually a file
elif not os.path.isfile(config_file):
logging.error('Specified config file does not exist')
logging.error('Not found in: "' + config_file + '"')
self.abort = True
# All good, read config
else:
# Load json config
fpointer = open(config_file)
data = fpointer.read()
fpointer.close()
# convert JSON to dict
config = json.loads(data)
# config['rules'] is simply a string array which looks like this:
# config['rules'] = [
# 'password',
# 'reset',
# 'delete',
# 'disable',
# 'drop',
# 'logout',
# ]
CrawlpySpider.rules = (
Rule(
LinkExtractor(
allow_domains=(self.allowed_domains),
unique=True,
deny=tuple(config['rules'])
),
callback='parse',
follow=False
),
)
Scrapy еще ползает страницы, которые присутствуют в config['rules']
и, следовательно, также попадает в logout
страницу. Таким образом, указанные страницы не запрещаются. Что мне здесь не хватает?
Update:
Я уже пробовал, установив CrawlpySpider.rules = ...
, а также self.rules = ...
внутри __init__
. Оба варианта не работают.
- Паук:
InitSpider
- Правила:
LinkExtractor
- Перед ползать: Ведение входа перед ползет
Я даже пытаются отрицать, что в моей parse
функции
# Dive deeper?
# The nesting depth is now handled via a custom middle-ware (middlewares.py)
#if curr_depth < self.max_depth or self.max_depth == 0:
links = LinkExtractor().extract_links(response)
for link in links:
for ignore in self.ignores:
if (ignore not in link.url) and (ignore.lower() not in link.url.lower()) and link.url.find(ignore) == -1:
yield Request(link.url, meta={'depth': curr_depth+1, 'referer': response.url})
Я тоже пробовал, и это не сработало. Я добавил эту информацию к моему вопросу. – cytopia
У InitSpider нет похожего на '_compile_rules' (как и CrawlSpider). По-видимому, похоже, что у InitSpider даже нет правил, поскольку он наследует только от Spider. CrawlSpider выполняет все это. – cytopia