Python Scrapy 301 重定向

标签 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

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

谢谢。

最佳答案

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

项目范围

您可以在 settings.py 文件中设置 HTTPERROR_ALLOWED_CODES = [301,302,...]。或者,如果您想为所有代码启用它,您可以改为设置 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

关于Python Scrapy 301 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38658247/

相关文章:

python - 如何处理这两个字典以获得 Python 中的新字典?

python - Django:如何在呈现 View 后更新模型?

python - 如何知道Python中对象的实例化位置?

python - 类型错误 : '_sre.SRE_Match' object has no attribute '__getitem__'

python-2.7 - 抓取由javascript生成的链接

python - scrapy 中的 Djangoitem

python - 让 Scrapy 跟随链接并收集数据

scrapy - 是不是scrapy可以直接使用Phantomjs下载页面源来渲染?

python - 信号特征识别

python - 如何在数据框中找到另一个没有循环的相关行