Python Scrapy 301重定向

Pav*_*aev 3 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
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

Gra*_*rus 13

要解析任何不是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
Run Code Online (Sandbox Code Playgroud)

请求范围

您可以meta在请求中handle_httpstatus_list = [301, 302,...]handle_httpstatus_all = True为所有请求设置这些密钥:

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

要了解更多信息,请参阅HttpErrorMiddleware