2012-12-28 77 views

回答

19

好了,所以在http://doc.scrapy.org/en/latest/topics/extensions.html的文件說,

The main entry point for a Scrapy extension (this also includes middlewares and pipelines) is the from_crawler class method which receives a Crawler instance which is the main object controlling the Scrapy crawler. Through that object you can access settings, signals, stats, and also control the crawler behaviour, if your extension needs to such thing.

,那麼你可以有一個函數來獲取設置。

@classmethod 
def from_crawler(cls, crawler): 
    settings = crawler.settings 
    my_setting = settings.get("MY_SETTING") 
    return cls(my_setting) 

履帶式引擎,然後用my_setting調用管道的初始化函數,就像這樣:

def __init__(self, my_setting): 
    self.my_setting = my_setting 

等功能都與self.my_setting訪問它,符合市場預期。

或者,在from_crawler()功能,您可以在crawler.settings對象從管道需要的,而不是拉他們全部在構造函數中傳遞給__init__(),然後訪問設置。

+0

的聲音非常複雜。沒有更簡單的方法來做到這一點,或者更好的解釋?你不能使用'scrapy.settings import Settings'嗎? – not2qubit

+1

@ user1147688我會使用這種方法,因爲它符合scrapy的基於依賴注入的內部API。你的建議可能會奏效,但它看起來並沒有任何保證,它將來會繼續,因爲內部的API可能會被移動。 – deceze

+0

@avaleske,這個作品很棒,但是你知道我們如何使用它來設置一個設置嗎?例如,在其他一些功能中,假設我想更改其中一個設置值,例如'download_delay'。我們能做到嗎? – thefoxrocks

18

your_spider.py中訪問Scrapy設置(在settings.py中定義)的方法很簡單。所有其他答案太複雜了。造成這種情況的原因是Scrapy文檔的維護非常差,加上近期更新&更改。在「設置」文檔「How to access settings」和"Settings API"中都沒有提供任何可行的例子。以下是一個示例,說明如何獲取當前的字符串。

以下行只需添加到your_spider.py

# To get your settings from (settings.py): 
from scrapy.utils.project import get_project_settings 
... 
class YourSpider(BaseSpider): 
    ... 
    def parse(self, response): 
     ... 
     settings = get_project_settings() 
     print "Your USER_AGENT is:\n%s" % (settings.get('USER_AGENT')) 
     ... 

正如你所看到的,就沒有必要使用@classmethod或重新定義from_crawler()__init__()功能。希望這可以幫助。

PS。我仍然不確定爲什麼使用from scrapy.settings import Settings不能以相同的方式工作,因爲它會是更明顯的導入選擇?

+0

儘管文檔建議使用@avaleske的方法,但我仍然更喜歡這種方式,因爲它的工作原理和理解速度更快。 –

+3

此方法**未識別[從命令行覆蓋的設置](http://doc.scrapy.org/zh-CN/0.24/topics/settings.html#command-line-options)。如果您需要此功能,請使用@ avaleske的答案。 –

13

正確的答案是:它取決於您想要訪問設置的管道中的哪個位置。

avaleske已經回答了,就好像您想要訪問管道process_item方法之外的設置,但很可能這是您要設置的位置,因此在Spider實例本身傳入時有更簡單的方法作爲論據。

class PipelineX(object): 

    def process_item(self, item, spider): 
     wanted_setting = spider.settings.get('WANTED_SETTING') 
+1

很棒的回答。對於我的項目,將邏輯放入'open_spider'方法更有意義,因爲我只在第一次加載蜘蛛時使用該值。 –

2

項目結構是非常平坦的,爲什麼不:

# pipeline.py 
from myproject import settings