scrapy小細節

1.配置文件settings.py內一定要使用大寫變量名,不然from_crawler函數中的crawler.settings無法加載

2.回調函數將請求添加到調度器一定要用yield,而不是return

3.scrapy配置的優先級:

  1. 在命令行中通過-s覆蓋設置,優先級最高
  2. 每個爬蟲中custom_settings中指定配置
  3. 項目settings文件指定配置
  4. scrapy命令行工具覆蓋的設置
  5. 默認的全局配置

4.訪問配置:

spider初始化中:需要重寫from_crawler方法。

@classmethod
def from_crawler(self, crawler, *args, **kwargs)
    return super(test, self).from_crawler(crawler, crawler.settings)

def __init__(self, settings):
    pass

spider實例方法中:

self.settings.get("SCHEDULER")

中間件中訪問:

@classmethod
def from_crawler(cls, crawler):
    return cls(crawler.settings)

5.主動關閉爬蟲的方法:

  1. 在中間件中: 注意在請求初始地址時,process_request和process_response裏關閉爬蟲會報錯
    def process_request(self, request, response, spider):
        ...
        spdier.crawler.engine.close_spider(spider, '關閉原因')

     

  2. 在爬蟲中:
    self.crawler.engine.close_spider(self, '關閉原因')

    爬蟲的dont_filter=False會影響中間件的return request執行,因爲已經請求過一遍可能會被過濾,scrapy默認開始過濾,所以想實現正常的請求過濾,請求異常時能return request,需要在return request之前request.dont_filter = True

6.當一個節點有子節點時,它的text()返回值字符串會以子節點爲單位被截斷,返回列表

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章