Scrapy - Yield URL when max redirects reached[301]

Viewed 347

Code

# -*- coding: utf-8 -*-
import scrapy
import pandas as pd
from ..items import Homedepotv2Item
from scrapy.http import HtmlResponse


class HomedepotspiderSpider(scrapy.Spider):
    name = 'homeDepotSpider'
    #allowed_domains = ['homedepot.com']

    start_urls = ['https://www.homedepot.com/p/305031636', 'https://www.homedepot.com/p/311456581']
    handle_httpstatus_list = [301]

def parseHomeDepot(self, response):

    #get top level item
    items = response.css('.pip-container-fluid')
    for product in items:
        item = Homedepotv2Item()

        productSKU = product.css('.modelNo::text').getall() #getSKU

        productURL = response.request.url #Get URL


        item['productSKU'] = productSKU
        item['productURL'] = productURL

        yield item

Terminal Messages

Without handle_httpstatus_list = [301]

2020-03-12 12:24:58 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (301) to <GET https://www.homedepot.com/p/ZLINE-Kitchen-and-Bath-ZLINE-30-in-Wall-Mount-Range-Hood-in-DuraSnow-%C3%91-Stainless-Steel-8687S-30-8687S-30/305031636> from <GET https://www.homedepot.com/p/ZLINE-Kitchen-and-Bath-ZLINE-30-in-Wall-Mount-Range-Hood-in-DuraSnow-%C3%91-Stainless-Steel-8687S-30-8687S-30/305031636>
2020-03-12 12:24:58 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.homedepot.com/p/ZLINE-Kitchen-and-Bath-ZLINE-30-in-Wooden-Wall-Mount-Range-Hood-in-Walnut-Includes-Remote-Motor-KBRR-RS-30/311456581>
{'productName': ['ZLINE 30 in. Wooden Wall Mount Range Hood in Walnut - '
                 'Includes  Remote Motor'],
 'productOMS': '311456581',
 'productPrice': ['                                    979.95'],
 'productSKU': ['KBRR-RS-30'],
 'productURL': 'https://www.homedepot.com/p/ZLINE-Kitchen-and-Bath-ZLINE-30-in-Wooden-Wall-Mount-Range-Hood-in-Walnut-Includes-Remote-Motor-KBRR-RS-30/311456581'}

2020-03-12 12:25:01 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (301) to <GET https://www.homedepot.com/p/ZLINE-Kitchen-and-Bath-ZLINE-30-in-Wall-Mount-Range-Hood-in-DuraSnow-%C3%91-Stainless-Steel-8687S-30-8687S-30/305031636> from <GET https://www.homedepot.com/p/ZLINE-Kitchen-and-Bath-ZLINE-30-in-Wall-Mount-Range-Hood-in-DuraSnow-%C3%91-Stainless-Steel-8687S-30-8687S-30/305031636>
2020-03-12 12:25:01 [scrapy.downloadermiddlewares.redirect] DEBUG: Discarding <GET https://www.homedepot.com/p/ZLINE-Kitchen-and-Bath-ZLINE-30-in-Wall-Mount-Range-Hood-in-DuraSnow-%C3%91-Stainless-Steel-8687S-30-8687S-30/305031636>: max redirections reached
2020-03-12 12:25:01 [scrapy.core.engine] INFO: Closing spider (finished)
2020-03-12 12:25:01 [scrapy.extensions.feedexport] INFO: Stored csv feed (1 items) in: stdout:

With handle_httpstatus_list = [301]

2020-03-12 12:27:30 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2020-03-12 12:27:31 [scrapy.core.engine] DEBUG: Crawled (301) <GET https://www.homedepot.com/p/305031636> (referer: None)
2020-03-12 12:27:31 [scrapy.core.engine] DEBUG: Crawled (301) <GET https://www.homedepot.com/p/311456581> (referer: None)
2020-03-12 12:27:31 [scrapy.core.engine] INFO: Closing spider (finished)

this is what I'm using to export to excel scrapy crawl homeDepotSpider -t csv -o - > "pathname"

The Problem

So the issue I had originally was 'https://www.homedepot.com/p/305031636' being ignored by my spider because the link would drop a the error code 301 (too many redirects). After researching the problem I found that handle_httpstatus_list = [301]should've fixed this issue. However when I use this piece of code, since the working link ('https://www.homedepot.com/p/311456581')redirects to a different page, it also gets ignored.

Essentially what I want to do is to crawl data from all URLs that don't have an

ERR_TOO_MANY_REDIRECTS  

but grab URLs from links that do have that error code and then export that data to excel.

Edit: A better way to ask my question: Since all URL's I'm working with go through a redirect, how can I handle pages that fail to redirect and grab those URLs?

Also this is not my entire program, I've only included parts that I thought were necessary for the program.

1 Answers

You can manually handle the 301 error code with something like:

class HomedepotspiderSpider(scrapy.Spider):
    name = 'my_spider'
    retry_max_count = 3

    start_urls = ['https://www.homedepot.com/p/305031636', 'https://www.homedepot.com/p/311456581']
    handle_httpstatus_list = [301]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.retries = {} # here are stored URL retries counts

    def parse(self, response):
        if response.status == 301:
            retries = self.retries.setdefault(response.url, 0)
            if retries < self.retry_max_count:
                self.retries[response.url] += 1
                yield response.request.replace(dont_filter=True)
            else:
                # ...
                # DO SOMETHING TO TRACK ERR_TOO_MANY_REDIRECTS AND SAVE response.url
                # ...

            return

Note that also a 302 code can be used to redirect.

Related