501错误ScraPy-未处理或不允许HTTP状态代码

时间:2019-04-07 09:53:28

标签: python python-3.x scrapy

解决了以上错误。通过SO,仅讨论403或404错误。

以下是我尝试使其工作的一些方法。

  • 将user_agent编辑为我的字符串
  • 检查了Reddit的robots.txt,但没有禁止我的抓取参数
  • 尝试调整URL和域(尽职调查)
  • 没有刮擦的外壳..相同的错误,但没有解释
  • 该网站可在笔记本电脑上的浏览器上运行
  • 选中了http 501,表示“未实现”或服务器不支持功能

和错误字段

2019-04-07 17:34:00 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2019-04-07 17:34:00 [scrapy.core.engine] INFO: Spider opened
2019-04-07 17:34:00 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2019-04-07 17:34:00 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2019-04-07 17:34:00 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (301) to <GET https://www.reddit.com/robots.txt> from <GET http://www.reddit.com/robots.txt>
2019-04-07 17:34:00 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.reddit.com/robots.txt> (referer: None)
2019-04-07 17:34:00 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (301) to <GET https://www.reddit.com/r/gameofthrones//> from <GET http://www.reddit.com/r/gameofthrones//>
2019-04-07 17:34:01 [scrapy.core.engine] DEBUG: Crawled (501) <GET https://www.reddit.com/r/gameofthrones//> (referer: None)
2019-04-07 17:34:01 [scrapy.spidermiddlewares.httperror] INFO: Ignoring response **<501 https://www.reddit.com/r/gameofthrones//>: HTTP status code is not handled or not allowed**
2019-04-07 17:34:01 [scrapy.core.engine] INFO: Closing spider (finished)

代码

class RedditbotSpider(scrapy.Spider):

    name = "redditgetter"
    allowed_domains = ['reddit.com']
    start_urls = ['http://www.reddit.com/r/gameofthrones/']
    custom_settings = {
       'FEED_URI' : 'tmp/redditdata.csv'
    }

    def parse(self, response):

        titles = response.css('.title.may-blank::text').extract()
        votes = response.css('.score.unvoted::text').extract()
        times = response.css('time::attr(title)').extract()

        for item in zip(titles,votes,times):

            scraped_info = {
                'title' : item[0],
                'vote' : item[1],
                'created_at' : item[2],
            }

            yield scraped_info

UPDATE:缩进并更正了“ //”之后的新错误。

2019-04-07 23:00:44 [scrapy.core.engine] INFO: Spider opened
2019-04-07 23:00:44 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2019-04-07 23:00:44 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2019-04-07 23:00:44 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (301) to <GET https://www.reddit.com/robots.txt> from <GET http://www.reddit.com/robots.txt>
2019-04-07 23:00:45 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.reddit.com/robots.txt> (referer: None)
2019-04-07 23:00:45 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (301) to <GET https://www.reddit.com/r/gameofthrones/> from <GET http://www.reddit.com/r/gameofthrones/>
2019-04-07 23:00:47 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.reddit.com/r/gameofthrones/> (referer: None)
2019-04-07 23:00:47 [scrapy.core.engine] INFO: Closing spider (finished)
2019-04-07 23:00:47 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 1287,
 'downloader/request_count': 4,
 'downloader/request_method_count/GET': 4,
 'downloader/response_bytes': 101351,
 'downloader/response_count': 4,
 'downloader/response_status_count/200': 2,
 'downloader/response_status_count/301': 2,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2019, 4, 7, 15, 0, 47, 452284),
 'log_count/DEBUG': 4,
 'log_count/INFO': 9,
 'memusage/max': 50294784,
 'memusage/startup': 50290688,
 'response_received_count': 2,
 'robotstxt/request_count': 1,
 'robotstxt/response_count': 1,
 'robotstxt/response_status_count/200': 1,
 'scheduler/dequeued': 2,
 'scheduler/dequeued/memory': 2,
 'scheduler/enqueued': 2,
 'scheduler/enqueued/memory': 2,
 'start_time': datetime.datetime(2019, 4, 7, 15, 0, 44, 502445)}
2019-04-07 23:00:47 [scrapy.core.engine] INFO: Spider closed (finished)

1 个答案:

答案 0 :(得分:3)

此问题与您的代码实现无关,只是URL中的错字。通过通过https://reqbin.com/u4xxuehu

501发送GET请求,我能够重现问题(https://www.reddit.com/r/gameofthrones//状态代码)

您只需要删除URL末尾的多余斜杠即可获得200 (OK)状态:https://reqbin.com/43le52w4


编辑有关reddit抓取的内容:您的代码没有错误,它成功获得了101351字节的响应(您可以通过在response.body方法中打印parse()来自己检查):{ {1}}。

问题在于您解析响应的方式。您使用的CSS选择器(例如'downloader/response_bytes': 101351)未返回任何内容,因为HTML中没有包含此类类的元素(请在浏览器中检查网页的源代码,并查找那些您正在尝试选择)。实际上,您会注意到Reddit通过为HTML元素分配晦涩的类来采取反爬网措施。

但是,在检查源代码时,事实证明,页面的末尾包含包装在response.css('.title.may-blank::text')中的JSON数据,其中包括有关帖子的信息(标题,赞词等)。您要提取的信息的结构如下:

<script id="data"></script>

您可以简单地加载和解析JSON数据以获得所需的字段。这是posts └── models └── postId ├── title ├── score └── created 方法的有效实现:

parse()

示例输出:

def parse(self, response):

    # get the contents inside <script id="data"></script>
    data = response.css('#data::text').get()
    # remove anything before { and after } to get valid JSON
    data = re.findall(r"{.*}",str(data), re.MULTILINE)[0];
    jsonresponse = json.loads(data)

    titles = []
    votes = []
    times = []
    for post in jsonresponse["posts"]["models"]:
        titles.append(jsonresponse["posts"]["models"][post]["title"])
        votes.append(jsonresponse["posts"]["models"][post]["score"])
        times.append(jsonresponse["posts"]["models"][post]["created"])

    for item in zip(titles,votes,times):
        scraped_info = {
                'title' : item[0],
                'vote' : item[1],
                'created_at' : item[2],
        }
        yield scraped_info

演示:https://repl.it/@glhr/55557800