Python Scrapy 301重定向

时间:2016-07-29 11:57:08

标签: python scrapy

在抓取指定网站时,我在打印重定向的网址(301重定向后的新网址)时遇到了一些问题。我的想法是只打印它们而不是刮掉它们。我目前的代码是:

import scrapy
import os
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class MySpider(CrawlSpider):
    name = 'rust'
    allowed_domains = ['example.com']
    start_urls = ['http://example.com']

    rules = (
        # Extract links matching 'category.php' (but not matching 'subsection.php')
        # and follow links from them (since no callback means follow=True by default).
        # Extract links matching 'item.php' and parse them with the spider's method parse_item
        Rule(LinkExtractor(), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        #if response.status == 301:
        print response.url

但是,这不会打印重定向的网址。任何帮助将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:12)

要解析任何不是200的响应,您需要执行以下操作之一:

项目范围

您可以在HTTPERROR_ALLOWED_CODES = [301,302,...]文件中设置settings.py设置。或者,如果您要为所有代码启用它,则可以设置HTTPERROR_ALLOW_ALL = True

蜘蛛宽

handle_httpstatus_list参数添加到蜘蛛中。在你的情况下像:

class MySpider(scrapy.Spider):
    handle_httpstatus_list = [301]
    # or 
    handle_httpstatus_all = True

请求范围的

您可以在请求metahandle_httpstatus_list = [301, 302,...]中为所有人设置这些handle_httpstatus_all = True个键:

scrapy.request('http://url.com', meta={'handle_httpstatus_list': [301]})

要了解详情,请参阅HttpErrorMiddleware