本文介绍了AttributeError: 'Spider' 对象没有属性 'table'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用scrapy.我有一个以以下内容开头的蜘蛛:

I'm working with scrapy. I have a spider that starts with:

class For_Spider(Spider):

    name = "for"
#    table = 'hello' # creating dummy attribute. will be overwritten

    def start_requests(self):

        self.table = self.dc # dc is passed in

我有以下管道:

class DynamicSQLlitePipeline(object):

    @classmethod
    def from_crawler(cls, crawler):
        # Here, you get whatever value was passed through the "table" parameter
        table = getattr(crawler.spider, "table")
        return cls(table)

    def __init__(self,table):
        try:
            db_path = "sqlite:///"+settings.SETTINGS_PATH+"\\data.db"
            db = dataset.connect(db_path)
            table_name = table[0:3]  # FIRST 3 LETTERS
            self.my_table = db[table_name]

当我启动蜘蛛时:

scrapy crawl for -a dc=input_string -a records=1

我明白了:

AttributeError: 'For_Spider' object has no attribute 'table'

如果我取消注释 'table' ,程序就会启动.我对为什么 'table' 有效但 self.table 无效感到困惑.有人能解释一下吗?

If I uncomment 'table' , the program will start. I'm confused about why 'table' works but self.table does not. Can someone explain this?

推荐答案

table 会起作用,因为它是 For_Spiderself.table 就在函数作用域内.self 表示实例本身,因此在这种情况下,您不需要在函数内部使用它(除非您在 __init__ 中定义它).
如果您尝试在函数作用域之外定义 self.table,则会出现错误.

table will work because it is a class attribute of For_Spider and self.table is just inside the function scope. self indicates the instance itself, so in that case inside the function you don't need to use it (unless you define it in __init__).
If you'll try defining self.table outside the function scope you'll get an error.

另外,尝试在两个类上使用 __dict__ 来查看它们的属性和功能
表注释:

Also, try using __dict__ on both classes to see their attributes and functions
With table commented:

{'doc': None, 'start_requests': , 'name': 'for', 'module': 'builtins'})

如你所见,没有table属性

表没有注释:

{'doc': None, 'start_requests': , 'table': 'hello', 'name': 'for', 'module': '内置'})

我希望这很清楚:>

这篇关于AttributeError: 'Spider' 对象没有属性 'table'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 20:19