按照官方的文档写的demo,只是多了个init函数,最终执行时提示没有_rules这个属性的错误日志如下:

 ......File "C:\ProgramData\Anaconda3\lib\site-packages\scrapy\spiders\crawl.py", line 82, in _parse_responsefor request_or_item in self._requests_to_follow(response):File "C:\ProgramData\Anaconda3\lib\site-packages\scrapy\spiders\crawl.py", line 60, in _requests_to_followfor n, rule in enumerate(self._rules):
AttributeError: 'TestSpider' object has no attribute '_rules'

出问题的spider代码如下:

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from newtest.items import NewtestItemclass TestSpider(CrawlSpider):def __init__(self,*args, **kwargs):self.headers = {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8','Accept-Encoding':'gzip, deflate','User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}name = 'test'allowed_domains = ['example.com']start_urls = ['http://www.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).Rule(LinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),# Extract links matching 'item.php' and parse them with the spider's method parse_itemRule(LinkExtractor(allow=('item\.php', )), callback='parse_item'),)def parse_item(self, response):self.logger.info('Hi, this is an item page! %s', response.url)item = scrapy.Item()item['id'] = response.xpath('//td[@id="item_id"]/text()').re(r'ID: (\d+)')item['name'] = response.xpath('//td[@id="item_name"]/text()').extract()item['description'] = response.xpath('//td[@id="item_description"]/text()').extract()return item

后来仔细看了下,跟官方不一样的就是自己重写了init初始化方法,而根据这个提示的日志,应该是覆盖了CrawlSpider的init方法但是没有调用父类的init导致_rules这个属性没有声明导致的。我们来看下CrawlSpider的源码:


所以如果我们的Spider是从CrawlSpider继承过来的,并且自己需要实现__init__ 方法的话,记住要调用父类的__init__方法保障能正常初始化crawlspider的属性。
修改后的代码如下:

第11行的super(TestSpider, self).__init__(*args, **kwargs) 是关键:

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from newtest.items import NewtestItemclass TestSpider(CrawlSpider):def __init__(self, *args, **kwargs):super(TestSpider, self).__init__(*args, **kwargs)  # 这里是关键self.headers = {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8','Accept-Encoding':'gzip, deflate','User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}name = 'test'allowed_domains = ['example.com']start_urls = ['http://www.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).Rule(LinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),# Extract links matching 'item.php' and parse them with the spider's method parse_itemRule(LinkExtractor(allow=('item\.php', )), callback='parse_item'),)def parse_item(self, response):self.logger.info('Hi, this is an item page! %s', response.url)item = scrapy.Item()item['id'] = response.xpath('//td[@id="item_id"]/text()').re(r'ID: (\d+)')item['name'] = response.xpath('//td[@id="item_name"]/text()').extract()item['description'] = response.xpath('//td[@id="item_description"]/text()').extract()return item

转载于:https://www.cnblogs.com/xiaocy66/p/10589277.html

Scrapy Crawl 运行出错 AttributeError: 'xxxSpider' object has no attribute '_rules' 的问题解决...相关推荐

  1. Python3.7 Scrapy crawl 运行出错解决方法

    Python3.7 Scrapy crawl 运行出错解决方法 参考文章: (1)Python3.7 Scrapy crawl 运行出错解决方法 (2)https://www.cnblogs.com/ ...

  2. Scrapy爬虫报错AttributeError: ‘NoneType‘ object has no attribute ‘write‘

    前言 一.报错 AttributeError: 'NoneType' object has no attribute 'write' 二.报错原因 1.piplines文件中的方法不能自定义的呢 开始 ...

  3. rosrun rqt_graph rqt_graph报警:AttributeError: ‘ElementTree‘ object has no attribute ‘getiterator‘

    一.问题描述: joes@joes:~$ rosrun rqt_graph rqt_graph Found metadata in lib /home/joes/.local/lib/python3. ...

  4. Spyder 运行出现 Reloaded modules: **AttributeError: 'NoneType' object has no attribute 'modules' 错误的解决方法

    问题描述: 刚开始学习python,有很多问题不懂,网上找了很久找不到答案,就把这个问题记下来,希望可以帮助到其他初学者 使用spyder运行以下代码: 第一次运行可以正常显示结果,第二次运行时报错: ...

  5. 运行项目时flask_sqlalchemy报错AttributeError: ‘LocalStack‘ object has no attribute ‘__ident_func__‘

    运行项目时flask_sqlalchemy报错AttributeError: 'LocalStack' object has no attribute '__ident_func__' 1.原因 2. ...

  6. web.py——运行错误【AttributeError: ‘StaticApp‘ object has no attribute ‘directory‘】

    问题描述 AttributeError("'StaticApp' object has no attribute 'directory'") Traceback (most rec ...

  7. AttributeError: 'dict' object has no attribute 'has_key'

    运行下面的代码: if (locals().has_key('data')):del datagc.collect() 出错: if (locals().has_key('data')): Attri ...

  8. 【报错记录】AttributeError: ‘xxx‘ object has no attribute ‘module‘

    文章目录 问题描述 问题分析与解决 总结 参考资料 问题描述 在跑代码时,报出 AttributeError: 'InpaintGenerator' object has no attribute ' ...

  9. Python错误:AttributeError: 'generator' object has no attribute 'next'解决办法

    今天在学习生成器对象(generation object)运行以下代码时,遇到了一个错误: #定义生成器函数 def liebiao(): for x in range(10): yield x #函 ...

最新文章

  1. [Spring MVC] - JSP + Freemarker视图解释器整合
  2. linux 字符串转数字排序,linux中sort命令排序功能实现方法
  3. android注解的作用,Android 用注解来提升代码质量
  4. 钉钉自带浏览器版本过低,导致Object.assign不兼容...
  5. Centos 6中模拟破坏MBR救援模式下修复
  6. offset Dimensions 详解
  7. ff删除httpwatch插件
  8. java模拟usb接口_Java练习:一个简单的USB接口程序设计
  9. 怎么样用计算机打字,如何使用电脑键盘练习打字【拼音打字】
  10. java 仙剑奇侠传_仙剑奇侠传-繁体版
  11. Markdown使用指南
  12. 数论题中(杜教筛)交换求和符号
  13. 字节跳动问我计算机网络,我一口气全答对!
  14. 关于iOS的通讯录开发权限的说明笔记
  15. 在Unity实现Canny边缘检测
  16. MDC是什么鬼?用法、源码一锅端
  17. 总结自适应网站的标准尺寸
  18. 回顾陆奇的传奇人生,下一站是“星辰和大海”
  19. 一个登录页面的测试用例——软件测试
  20. 操作系统无法识别声卡的解决方法

热门文章

  1. 985程序员4年50万仍被二本学医亲戚酸:学会这3点,才能笑到最后
  2. 最好用的虚拟机软件----VMware详细图文教程
  3. mysql 查看autocommit_手把手教你分析Mysql死锁问题
  4. 从源码角度解释 fragment 坑(一)
  5. c++最快简洁提供http文件服务
  6. 我的一些学习经验:视频流媒体方面
  7. 【kafka】kafka消费者报错INVALID_FETCH_SESSION_EPOCH
  8. 【Elasticsearch】揭秘 Elasticsearch 分片分配
  9. 【Elasticsearch】Elasticsearch 5.1.2滚动升级至 5.6.4
  10. 95-10-045-启动-LogDirFailureChannel