如何在scrapy中禁用缓存?

sag*_*gar 6 caching scrapy

我正在尝试抓取特定网站上的网页scrapy.Request().对于我发送的不同Cookie,网页会有所不同.

如果我逐个向网页发出请求,它会给我正确的结果,但是当我将这些cookie发送到for循环中时,它会给我相同的结果.我认为scrapy正在为我创建缓存,在第二个请求中它从缓存中获取响应.这是我的代码:

def start_requests(self):
        meta = {'REDIRECT_ENABLED':True}
        productUrl = "http://xyz"
        cookies = [{'name': '', 'value': '=='},{'name': '', 'value': '=='}]
        for cook in cookies:

            header = {"User-Agent":"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36"}
            productResponse = scrapy.Request(productUrl,callback=self.parseResponse,method='GET',meta=meta,body=str(),cookies=[cook],encoding='utf-8',priority=0,dont_filter=True)
            yield productResponse


def parseResponse(self,response): 
     selector = Selector(response)
     print selector.xpath("xpaths here").extract()
     yield None
Run Code Online (Sandbox Code Playgroud)

我希望print语句应该为这两个请求提供不同的结果.

如果有任何不明确的地方,请在评论中提及.

Nir*_*gar 8

缓存可以通过两种方式禁用

  1. 在setting.py文件中更改与缓存相关的设置中的值。通过保持HTTPCACHE_ENABLED = False
  2. 或者可以在运行时完成“ scrapy crawl crawl-name --set HTTPCACHE_ENABLED = False

  • FWIW,我遇到了2的异常。-但它适用于:--set HTTPCACHE_ENABLED = 0 (5认同)

Lev*_*von 5

在这里,我假设您只想避免仅缓存特定请求。

对于此示例,这意味着避免缓存这些请求start_requests并缓存所有其他请求(您可能在 下parseResponse)。

为此,只需productResponse.meta['dont_cache'] = True在您的代码中添加一行并HTTPCACHE_ENABLED=True在下面设置settings.py

现在所有其他请求都将被缓存。

def start_requests(self):
        meta = {'REDIRECT_ENABLED':True}
        productUrl = "http://xyz"
        cookies = [{'name': '', 'value': '=='},{'name': '', 'value': '=='}]
        for cook in cookies:

            header = {"User-Agent":"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36"}
            productResponse = scrapy.Request(productUrl,callback=self.parseResponse,method='GET',
                                             meta=meta,body=str(),cookies=[cook],
                                             encoding='utf-8',priority=0,dont_filter=True)
            productResponse.meta['dont_cache'] = True
            yield productResponse

def parseResponse(self,response): 
     selector = Selector(response)
     print selector.xpath("xpaths here").extract()
     yield None
Run Code Online (Sandbox Code Playgroud)