请问是哪个文件或地方的出错,好像是JobBoleArticleItem

来源:4-15 items的定义和使用 - 2

keannen

2020-02-02

***********************************报错代码**************************************

G:\Evns\ArticleSpider\venv\Scripts\python.exe G:/Evns/ArticleSpider/main.py
2020-02-02 10:13:45 [scrapy.utils.log] INFO: Scrapy 1.8.0 started (bot: ArticleSpider)
2020-02-02 10:13:45 [scrapy.utils.log] INFO: Versions: lxml 4.4.2.0, libxml2 2.9.5, cssselect 1.1.0, parsel 1.5.2, w3lib 1.21.0, Twisted 19.10.0, Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)], pyOpenSSL 19.1.0 (OpenSSL 1.1.1d  10 Sep 2019), cryptography 2.8, Platform Windows-10-10.0.17134-SP0
2020-02-02 10:13:45 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'ArticleSpider', 'NEWSPIDER_MODULE': 'ArticleSpider.spiders', 'SPIDER_MODULES': ['ArticleSpider.spiders']}
2020-02-02 10:13:45 [scrapy.extensions.telnet] INFO: Telnet Password: 5cde1b6e0a2a404d
2020-02-02 10:13:45 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.logstats.LogStats']
2020-02-02 10:13:45 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2020-02-02 10:13:45 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2020-02-02 10:13:45 [scrapy.middleware] INFO: Enabled item pipelines:
['scrapy.pipelines.images.ImagesPipeline',
 'ArticleSpider.pipelines.ArticlespiderPipeline']
2020-02-02 10:13:45 [scrapy.core.engine] INFO: Spider opened
2020-02-02 10:13:45 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2020-02-02 10:13:45 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2020-02-02 10:13:46 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (301) to <GET https://news.cnblogs.com/> from <GET http://news.cnblogs.com/>
2020-02-02 10:13:46 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://news.cnblogs.com/> (referer: None)
2020-02-02 10:13:46 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://news.cnblogs.com/n/654235/> (referer: https://news.cnblogs.com/)
2020-02-02 10:13:46 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://news.cnblogs.com/NewsAjax/GetAjaxNewsInfo?contentId=654235> (referer: https://news.cnblogs.com/n/654235/)
2020-02-02 10:13:47 [scrapy.core.scraper] ERROR: Spider error processing <GET https://news.cnblogs.com/NewsAjax/GetAjaxNewsInfo?contentId=654235> (referer: https://news.cnblogs.com/n/654235/)
Traceback (most recent call last):
  File "G:\Evns\ArticleSpider\venv\lib\site-packages\scrapy\utils\defer.py", line 102, in iter_errback
    yield next(it)
  File "G:\Evns\ArticleSpider\venv\lib\site-packages\scrapy\core\spidermw.py", line 84, in evaluate_iterable
    for r in iterable:
  File "G:\Evns\ArticleSpider\venv\lib\site-packages\scrapy\spidermiddlewares\offsite.py", line 29, in process_spider_output
    for x in result:
  File "G:\Evns\ArticleSpider\venv\lib\site-packages\scrapy\core\spidermw.py", line 84, in evaluate_iterable
    for r in iterable:
  File "G:\Evns\ArticleSpider\venv\lib\site-packages\scrapy\spidermiddlewares\referer.py", line 339, in <genexpr>
    return (_set_referer(r) for r in result or ())
  File "G:\Evns\ArticleSpider\venv\lib\site-packages\scrapy\core\spidermw.py", line 84, in evaluate_iterable
    for r in iterable:
  File "G:\Evns\ArticleSpider\venv\lib\site-packages\scrapy\spidermiddlewares\urllength.py", line 37, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "G:\Evns\ArticleSpider\venv\lib\site-packages\scrapy\core\spidermw.py", line 84, in evaluate_iterable
    for r in iterable:
  File "G:\Evns\ArticleSpider\venv\lib\site-packages\scrapy\spidermiddlewares\depth.py", line 58, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "G:\Evns\ArticleSpider\ArticleSpider\spiders\jobbole.py", line 81, in parse_nums
    article_item["praose_nums"] = praise_nums
  File "G:\Evns\ArticleSpider\venv\lib\site-packages\scrapy\item.py", line 98, in __setitem__
    (self.__class__.__name__, key))
KeyError: 'JobBoleArticleItem does not support field: praose_nums'
2020-02-02 10:13:47 [scrapy.core.engine] INFO: Closing spider (finished)
2020-02-02 10:13:47 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 991,
 'downloader/request_count': 4,
 'downloader/request_method_count/GET': 4,
 'downloader/response_bytes': 20962,
 'downloader/response_count': 4,
 'downloader/response_status_count/200': 3,
 'downloader/response_status_count/301': 1,
 'elapsed_time_seconds': 1.066412,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2020, 2, 2, 2, 13, 47, 12632),
 'log_count/DEBUG': 4,
 'log_count/ERROR': 1,
 'log_count/INFO': 10,
 'request_depth_max': 2,
 'response_received_count': 3,
 'scheduler/dequeued': 4,
 'scheduler/dequeued/memory': 4,
 'scheduler/enqueued': 4,
 'scheduler/enqueued/memory': 4,
 'spider_exceptions/KeyError': 1,
 'start_time': datetime.datetime(2020, 2, 2, 2, 13, 45, 946220)}
2020-02-02 10:13:47 [scrapy.core.engine] INFO: Spider closed (finished)

Process finished with exit code 0

写回答

3回答

keannen

提问者

2020-02-02

我重新看了几遍已经解决了

0
1
bobby
好的,
2020-02-03
共1条回复

keannen

提问者

2020-02-02

*************Jobbole.py*************

# -*- coding: utf-8 -*-

from urllib import parse

import scrapy   #scrapy是异步io框架,没有多线程,没有引入消息队列

import requests

from ArticleSpider.utils import common

from ArticleSpider.items import JobBoleArticleItem

import re

import json

from scrapy import Request


class JobboleSpider(scrapy.Spider):

    name = 'jobbole'

    allowed_domains = ['news.cnblogs.com']

    start_urls = ['http://news.cnblogs.com/']


    def parse(self, response):

        # 1、获得新闻列表页中的新闻url并交给scrapy进行下载后调用相应的解析方法

        # 2、获取下一页的url并交给scrapy下载,下载完成后交给parse继续跟进


        # urls = response.css('div#news_list h2 a::attr(href)').extract()

        post_nodes = response.css('#news_list .news_block')[1:2]

        for post_node in post_nodes:

            image_url = post_node.css('.entry_summary a img::attr(src)').extract_first("")

            post_url = post_node.css('h2 a::attr(href)').extract_first("")

            yield Request(url=parse.urljoin(response.url,post_url),meta={"front_image_url":image_url},callback=self.parse_detail)


        #提取下一页并交给scrapy进行下载

        # next_url = response.css("div.pager a:last-child::text").extract_first("")

        # next_url = response.xpath("//a[contains(text(),'Next >')]/@href").extract_first("")

        # yield Request(url=parse.urljoin(response.url, next_url), callback=self.parse)

        # if next_url == "Next >":

        #     next_url = response.css("div.pager a:last-child::attr(href)").extract_first("")

        #     yield Request(url=parse.urljoin(response.url,next_url),callback=self.parse)


    def parse_detail(self,response):

        match_re = re.match(".*?(\d+)",response.url)

        if match_re:

            post_id = match_re.group(1)

            article_item = JobBoleArticleItem()

            #xpath获取方式

            # title = response.xpath("//*[@id='news_title']//a/text()").extract_first("")

            # create_date = response.xpath("//*[@id='news_info']//*[@class='time']/text()").extract_first("")

            # content = response.xpath("//*[@id='news_content']").extract()[0]

            # tag_list = response.xpath("//*[@id='news_tags']//a/text()").extract()


            #css获取方式

            title = response.css("#news_title a::text").extract_first("")

            create_date = response.css("#news_info .time::text").extract_first("")

            match_re = re.match(".*?(\d+.*)",create_date)

            if match_re:

                create_date = match_re.group(1)

            content = response.css("#news_content").extract()[0]

            tag_list = response.css(".news_tags a::text").extract()

            tags = ",".join(tag_list)


            # html = requests.get(parse.urljoin(response.url,"/NewsAjax/GetAjaxNewsInfo?contentId={}".format(post_id)))

            # j_data = json.loads(html.text)

            article_item["title"] = title

            article_item["create_date"] = create_date

            article_item["content"] = content

            article_item["tags"] = tags

            article_item["title"] = title

            article_item["url"] = response.url

            article_item["front_image_url"] = [response.meta.get("front_image_url", "")]


            yield Request(url=parse.urljoin(response.url, "/NewsAjax/GetAjaxNewsInfo?contentId={}".format(post_id)),

                          meta={"article_item":article_item},callback=self.parse_nums)


            # praise_nums = j_data["DiggCount"]

            # fav_nums = j_data["TotalView"]

            # comment_nums = j_data["CommentCount"]



    def parse_nums(self,response):

        j_data = json.loads(response.text)

        article_item = response.meta.get("article_item", "")

        praise_nums = j_data["DiggCount"]

        fav_nums = j_data["TotalView"]

        comment_nums = j_data["CommentCount"]


        article_item["praose_nums"] = praise_nums

        article_item["fav_nums"] = fav_nums

        article_item["comment_nums"] = comment_nums

        article_item["url_object_id"] = common.get_md5(article_item["url"])


        yield article_item


0
0

keannen

提问者

2020-02-02

********items.py**********

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class ArticlespiderItem(scrapy.Item):
   # define the fields for your item here like:
   # name = scrapy.Field()
   pass

class JobBoleArticleItem(scrapy.Item):
   title = scrapy.Field()
   create_date = scrapy.Field()
   url = scrapy.Field()
   url_object_id = scrapy.Field()
   front_image_url = scrapy.Field()
   front_image_path = scrapy.Field()
   praise_nums = scrapy.Field()
   comment_nums = scrapy.Field()
   fav_nums = scrapy.Field()
   tags = scrapy.Field()
   content = scrapy.Field()

0
0

Scrapy打造搜索引擎 畅销4年的Python分布式爬虫课

带你彻底掌握Scrapy,用Django+Elasticsearch搭建搜索引擎

5796 学习 · 6290 问题

查看课程