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

 ......
File "C:\ProgramData\Anaconda3\lib\site-packages\scrapy\spiders\crawl.py", line 82, in _parse_response
for 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_follow
for 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 NewtestItem class 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_item
Rule(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 NewtestItem class 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_item
Rule(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

Scrapy Crawl 运行出错 AttributeError: 'xxxSpider' object has no attribute '_rules' 的问题解决的更多相关文章

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

    安装的是Python3.7,装上依赖包和scrapy后运行爬虫命令出错 File "D:\Python37\lib\site-packages\scrapy\extensions\telne ...

  2. 提示AttributeError: 'module' object has no attribute 'HTTPSHandler'解决方法

    今天在新机器上安装sqlmap,运行提示AttributeError: 'module' object has no attribute 'HTTPSHandler' 网上找了找资料,发现一篇文章ht ...

  3. python 脚本运行时报错: AttributeError: 'module' object has no attribute ***

    最近在编写Python脚本过程中遇到一个问题比较奇怪:Python脚本完全正常没问题,但执行总报错"AttributeError: 'module' object has no attrib ...

  4. Django 运行报异常:AttributeError: 'str' object has no attribute 'get'

    Technorati Tags: Python,Django,Web 在使用django.contrib.auth用户机制进行用户的验证.登录.注销操作时,遇到这个异常. 首先是写了一个登录的视图,要 ...

  5. 在运行create_list.sh时候报错:AttributeError: 'module' object has no attribute 'LabelMap'

    Traceback (most recent call last):File "/opt/xuben-project/caffe/data/VOC0712/../../scripts/cre ...

  6. python3.x运行的坑:AttributeError: 'str' object has no attribute 'decode'

    1.Python3.x和Python2.X版本有一些区别,我遇到了两个问题如下: a.第一个报:mysqlclient 1.3版本不对: 解决办法:注释掉这行即可: b.第二个报:字符集的问题: 报错 ...

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

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

  8. Python AttributeError: 'Module' object has no attribute 'STARTF_USESHOWINDOW'

    夫学须志也,才须学也,非学无以广才,非志无以成学.--诸葛亮 生活有度,自得慈铭 --杜锦阳 今天新来的同事安装环境遇到个莫名其妙的问题: AttributeError: 'Module' objec ...

  9. 解决opencv:AttributeError: 'NoneType' object has no attribute 'copy'

    情况一: 路径中有中文,更改即可 情况二:可以运行代码,在运行结束时显示 AttributeError: 'NoneType' object has no attribute 'copy' 因为如果是 ...

随机推荐

  1. JSON数据写入和解析

    如何写入JSON 需要第三方jar包,JSON包 //写入json数据 public static String sendJson() { JSONObject json = new JSONObje ...

  2. unzip文件解压

    1.记录下,遇到.zip的安装包,指定解压到某个地方 格式:unzip      压缩包名.zip  -d   存放路径  

  3. 目标检测算法之YOLOv3

    参考地址:https://blog.csdn.net/leviopku/article/details/82660381 YOLO v3结构图 DBL:卷积+BN+leaky relu,是v3的最小组 ...

  4. nginx 监控脚本

    [root@Client_Download_Source shell]# cat start.nginx.sh #!/bin/bash while true do sleep 2 check=`net ...

  5. LOCK TABLES 和 UNLOCK TABLES

    MySQLdump的时LOCK TABLES 和 UNLOCK TABLES 在mysqldump后的数据中会发现有 LOCK TABLES tables_name WRITE;和结尾处有 UNLOC ...

  6. js中的原型

    一:原型属性 函数本身也是一个包含了方法和属性的对象. 定义一个函数foo(),访问其他对象一样访问该函数的属性: function foo(a, b) { return a * b; } foo.l ...

  7. Senparc.Weixin微信开发(1) 开发验证

    官方系列教程 http://www.cnblogs.com/szw/archive/2013/05/20/3089479.html 登录微信公众平台后-左侧找到开发--启用服务器配置 这样,我们才可以 ...

  8. CSS预处理器—Sass、LESS和Stylus

    http://www.w3cplus.com/css/css-preprocessor-sass-vs-less-stylus-2.html 一.什么是CSS预处器 CSS预处理器定义了一种新的语言, ...

  9. jQuery中的extend()方法

    通常我们使用jquery的extend时,大都是为了实现默认字段的覆盖,即若传入某个字段的值,则使用传入值,否则使用默认值.如下面的代码: function getOpt(option){ var _ ...

  10. [BZOJ1977][BeiJing2010组队]次小生成树

    题解: 首先要证明一个东西 没有重边的图上 次小生成树由任何一颗最小生成树替换一条边 但是我不会证啊啊啊啊啊啊啊 然后就很简单了 枚举每一条边看看能不能变 但有一个特殊情况就是,他和环上的最大值相等, ...