11
votes

I wrote a small scrapy spider. Following is my code

class ElectronicsSpider(scrapy.Spider):
    name = "electronics"
    allowed_domains = ["www.olx.com"]
    start_urls = ['http://www.olx.com/']

    def parse(self, response):
        pass

My question is, I want to read the name,allowed_domains and start_urls using setting. How can i do this?

I tried importing

 from scrapy.settings import Settings

also tried this

 def __init__(self,crawler):
        self.settings = crawler.settings

but I got none/error. Help me to read settings in my spider?

3
Because name, allowed_domains etc. are not settings, but spider class attributes. If you need to read settings from your spider code, then you can use just self.settings because it's prepopulated for you by Scrapy. - Tomáš Linhart
can you please help me to achieve this @Tomáš Linhart - Vigneshwaran
I think my comment is self-contained. If you need definitive answer, you need to share more info about from where exactly you need to read what. - Tomáš Linhart

3 Answers

20
votes
from scrapy.utils.project import get_project_settings

settings=get_project_settings()
print settings.get('NAME')

Using this code we can read data from settings file...

9
votes

self.settings is not yet initiated in __init__(). You can check self.settings in start_requests().

def start_requests(self): 
    print self.settings
2
votes

I think if you want to access scrapy settings.py then answer from @Sellamani is good. But I guess name,allowed_domains and start_urls are not variables defined in settings.py. But if you want to have the same knd of arrangement then make your own config file like this, yourown.cfg :

[Name]
crawler_name=electronics

[DOMAINS]
allowed_domains=http://example.com

and then in your program use ConfigParser module like this to access yourown.cfg :

import ConfigParser
config = ConfigParser.ConfigParser()
config.read('yourown.cfg') # Assuming it is at the same location
name=config.getint('NAME', 'crawler_name')
allowed_domains=config.getint('DOMAINS', 'allowed_domains')