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' 因为如果是 ...
随机推荐
- 调试阶段 获取微信小程序openid
wx.login({ success: function(res) { //首先获取用户code //res.code wx.request({ url: 'https://api.weixin.qq ...
- 将眼底图片生成的txt文件进行格式化处理
# -*- coding: utf-8 -*- """ 将图片转换生成的txt文件进行格式化处理 """ import os import ...
- Python关键字及其用法
Python有哪些关键字 -Python常用的关键字 and, del, from, not, while, as, elif, global, or, with, assert, else, if ...
- h5在手机端实现简单复制
<a href="https://blog-static.cnblogs.com/files/ruanqin/clipboard.min.js">下载clipborrd ...
- Windows Server 2012 R2 设置 NTP 服务
其实和以前的server版本配置没啥不一样 都是先改注册表: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Config\ ...
- POJ 2243 简单搜索 (DFS BFS A*)
题目大意:国际象棋给你一个起点和一个终点,按骑士的走法,从起点到终点的最少移动多少次. 求最少明显用bfs,下面给出三种搜索算法程序: // BFS #include<cstdio> #i ...
- 「BZOJ3791」作业
题解: 比正解的做法要复杂 正解直接确定了最多有2k-1段 并且可以证明2k-1是一定可以覆盖的 于是可以直接dp 我的想法是先覆盖一段黑的,然后白的覆盖上去 所以f[i][0/1/2][0/1/2] ...
- 【前端基础系列】slice方法将类数组转换数组实现原理
问题描述 在日常编码中会遇到将类数组对象转换为数组的问题,其中常用到的一种方式使用Array.prototype.slice()方法. 类数组对象 所谓的类数组对象,JavaScript对它们定义为: ...
- ssh登陆linux服务器 实际场景讲解 让你管理服务器更安全
很多时候我们管理linux系统,都谁使用ssh登陆,因为都知道ssh是加密传输的协议的,可以有效保证我们与 服务器之间的数据通信安全.但是我们忽略了一点,但是登陆的时候我们是输入的账号和密码,这一点其 ...
- 前端本地存储localStorage
1.突破cookie 4K限制,一般浏览器支持5M 2.增 删 改 查 <!DOCTYPE html> <html lang="en"> <head& ...