Scrapy Crawl 运行出错 AttributeError: 'xxxSpider' object has no attribute '_rules' 的问题解决
按照官方的文档写的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' 的问题解决的更多相关文章
- Python3.7 Scrapy crawl 运行出错解决方法
安装的是Python3.7,装上依赖包和scrapy后运行爬虫命令出错 File "D:\Python37\lib\site-packages\scrapy\extensions\telne ...
- 提示AttributeError: 'module' object has no attribute 'HTTPSHandler'解决方法
今天在新机器上安装sqlmap,运行提示AttributeError: 'module' object has no attribute 'HTTPSHandler' 网上找了找资料,发现一篇文章ht ...
- python 脚本运行时报错: AttributeError: 'module' object has no attribute ***
最近在编写Python脚本过程中遇到一个问题比较奇怪:Python脚本完全正常没问题,但执行总报错"AttributeError: 'module' object has no attrib ...
- Django 运行报异常:AttributeError: 'str' object has no attribute 'get'
Technorati Tags: Python,Django,Web 在使用django.contrib.auth用户机制进行用户的验证.登录.注销操作时,遇到这个异常. 首先是写了一个登录的视图,要 ...
- 在运行create_list.sh时候报错:AttributeError: 'module' object has no attribute 'LabelMap'
Traceback (most recent call last):File "/opt/xuben-project/caffe/data/VOC0712/../../scripts/cre ...
- python3.x运行的坑:AttributeError: 'str' object has no attribute 'decode'
1.Python3.x和Python2.X版本有一些区别,我遇到了两个问题如下: a.第一个报:mysqlclient 1.3版本不对: 解决办法:注释掉这行即可: b.第二个报:字符集的问题: 报错 ...
- AttributeError: 'dict' object has no attribute 'has_key'
运行下面的代码: if (locals().has_key('data')): del data gc.collect() 出错: if (locals().has_key('data')): Att ...
- Python AttributeError: 'Module' object has no attribute 'STARTF_USESHOWINDOW'
夫学须志也,才须学也,非学无以广才,非志无以成学.--诸葛亮 生活有度,自得慈铭 --杜锦阳 今天新来的同事安装环境遇到个莫名其妙的问题: AttributeError: 'Module' objec ...
- 解决opencv:AttributeError: 'NoneType' object has no attribute 'copy'
情况一: 路径中有中文,更改即可 情况二:可以运行代码,在运行结束时显示 AttributeError: 'NoneType' object has no attribute 'copy' 因为如果是 ...
随机推荐
- angular-cli ng build 打包完成后 打开文件显示空白
将index.html 里面的<base href="/"> 改为<base href="./"> 前面加一个 点 就好了,然后再次打包 ...
- Python杂写1
一:编程及编程语言介绍 编程的目的:人把自己的思想流程表达出来,让计算机按照这种思想去做事,把人给解放出来. 编程语言:简单的说就是一种语言,是人和计算机沟通的语言. 编程:例如Python,利用Py ...
- sublime快捷键的使用
Sublime text 3是码农最喜欢的代码编辑器,每天和代码打交道,必先利其器,掌握基本的代码编辑器的快捷键,能让你打码更有效率.刚开始可能有些生疏,只要花一两个星期坚持使用并熟悉这些常用的快捷键 ...
- python 通用装饰器,带有参数的装饰器,
# 使用装饰器对有返回值的函数进行装饰# def func(functionName): # print('---func-1----') # def func_in(): # print(" ...
- 解决response.setHeader("Content-disposition" 中文乱码问题
Content-Disposition中文乱码 Response.setHeader(”Content-Disposition”, “attachment; filename=” + fileName ...
- SqlServer2012清除日志文件
SqlServer在使用中会产生大量的日志文件,当不需要的时候可以进行删除. 删除方式: 右键数据库-->任务-->收缩-->文件 进入收缩文件页面,按照如下配置就可以了 有时候收缩 ...
- python---实现多个有序列表的合并
我觉得不用抄书上的代码. 遇到实现问题,应该结合python本身的功能去解决. 比如,当合并有序列表时,为什么一定要一项一项比较,而不是使用list的sort函数呢? # coding = utf-8 ...
- C#学习-类的成员
定义完类之后,还需在类中定义成员. 类的成员包括字段.属性.方法和构造函数等,它们与类一样,也都有自己的访问权限.以下是 public,同一个程序集或引用该程序集的其他程序集都可以访问 private ...
- 一个良好划分Activity创建步骤的BaseActivity
一个Activity的创建过程其实包含几个不同的步骤,基本上都是在onCreate函数中完成的,这些步骤主要有: 设置页面的布局文件 初始化页面包含的控件 设置页面控件的点击响应事件 处理页面的业务逻 ...
- C语言整理——文件系统和文件访问
标准C中规定了文件系统的访问和对文件本身的访问.不管是windows系统或者是泛unix系统,都实现了这些接口.在了解这些知识后,跨平台编程也将非常容易. 对文件系统的访问接口有: chdrive() ...