使用适当的解析器处理重定向响应

时间:2013-07-12 09:27:37

标签: python redirect scrapy

我正在用scrapy抓取一个网站。 parse方法首先提取所有类别链接,然后将回调请求发送到parse_category

问题是,如果任何类别有一个产品,它会重定向到产品页面。我的parse_category无法识别此页面。

现在如何使用产品页面解析器解析重定向的类别页面?

这是一个例子。

  1. parse找到3个类别页面。
    1. http://example.com/products/samsung
    2. http://example.com/products/dell
    3. http://example.com/products/apple
  2. pare_category调用所有这些页面。每个都返回一个包含产品列表的html页面。但apple只有一个产品iMac 27"。所以它重定向到http://example.com/products/apple/imac_27。这是一个产品页面。类别解析无法解析它。
  3. 我需要在这种情况下调用产品解析方法parse_product。我该怎么做?

    我可以在parse_category方法中添加一些逻辑并调用parse_product。我不想要它。我想scrapy会这样做。但是,是的,我将提供网址模式或任何其他必要的信息。

    这是代码。

    class ExampleSpider(BaseSpider):
        name = u'example.com'
        allowed_domains = [u'www.example.com']
        start_urls = [u'http://www.example.com/category.aspx']
    
        def parse(self, response):
            hxs = HtmlXPathSelector(response)
    
            anchors = hxs.select('/xpath')
            for anchor in anchors:
                yield Request(urljoin(get_base_url(response), anchor), callback=self.parse_category)
    
        def parse_category(self, response):
            hxs = HtmlXPathSelector(response)
    
            products = hxs.select(products_xpath).extract()
            for url in products:
                yield Request(url, callback=self.parse_product)
    
    
        def parse_product(self, response):
            # product parsing ...
            pass
    

1 个答案:

答案 0 :(得分:1)

您可以选择编写实现process_response方法的middleware。每当您的回复是针对产品网址而非类别时,请为您的产品解析器创建copy of the Request objectchange the callback function

最后,从中间件返回新的Request对象。注意:可能需要为dont_filter设置TrueRequest,以确保DupeFilter不会过滤请求。