简体   繁体   English

IndentationError:意外的缩进错误

[英]IndentationError: unexpected indent error

I am new to Python and am getting this error: 我是Python新手,我收到此错误:

Traceback (most recent call last):
  File "/usr/local/bin/scrapy", line 4, in <module>
    execute()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/cmdline.py", line 130, in execute
    _run_print_help(parser, _run_command, cmd, args, opts)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/cmdline.py", line 96, in _run_print_help
    func(*a, **kw)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/cmdline.py", line 136, in _run_command
    cmd.run(args, opts)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/commands/crawl.py", line 42, in run
    q = self.crawler.queue
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/command.py", line 31, in crawler
    self._crawler.configure()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/crawler.py", line 36, in configure
    self.spiders = spman_cls.from_settings(self.settings)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/spidermanager.py", line 33, in from_settings
    return cls(settings.getlist('SPIDER_MODULES'))
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/spidermanager.py", line 23, in __init__
    for module in walk_modules(name):
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/utils/misc.py", line 65, in walk_modules
    submod = __import__(fullpath, {}, {}, [''])
  File "/my_crawler/empt/empt/spiders/empt_spider.py", line 59
    check_exists_sql = "SELECT * FROM LINKS WHERE link = '%s' LIMIT 1" % item['link']
    ^
IndentationError: unexpected indent

On this bit of code: 在这段代码上:

def parse_item(self, response):
    hxs = HtmlXPathSelector(response)
    sites = hxs.select('//a[contains(@href, ".mp3")]/@href').extract()
    items = [ ]

    #for site in sites:
        #link = site.select('a/@href').extract()
        #print site
    for site in sites:
        item = EmptItem()
        item['link'] = site #site.select('a/@href').extract()

        #### DB INSERT ATTEMPT ###
        #MySQL Test

        #open db connection
        db = MySQLdb.connect("localhost","root","str0ng","TESTDB")

        #prepare a cursor object using cursor() method
        cursor = db.cursor()

        #see if any links in the DB match the crawled link
        check_exists_sql = "SELECT * FROM LINKS WHERE link = '%s' LIMIT 1" % item['link']

        cursor.execute(check_exists_sql)

        if cursor.rowcount = 0:
            #prepare SQL query to insert a record into the db.
            sql = "INSERT INTO LINKS ( link ) VALUES ( '%s')" % item['link']

            try:
                #execute the sql command
                cursor.execute(sql)
                #commit your changes to the db
                db.commit()
            except:
                #rollback on error
                db.rollback()

                #fetch a single row using fetchone() method.
                #data = cursor.fetchone()

                #print "Database version: %s " % data

            #disconnect from server
            db.close()

            ### end mysql

        items.append(item)
    return items​

While the indentation errors are obvious in the StackOverflow page, they may not be in your editor. 虽然StackOverflow页面中的缩进错误很明显,但它们可能不在您的编辑器中。 You have a mix of different indentation types here, 1, 4 and 8 spaces. 这里有不同的缩进类型,1,4和8个空格。 You should always use four spaces for indentation, as per PEP8 . 根据PEP8 ,您应该始终使用四个空格进行缩进。 You should also avoid mixing tabs and spaces . 您还应避免混合制表符和空格

I also recommend that you try to run your script using the ' -tt ' command-line option to determine when you accidentally mix tabs and spaces. 我还建议您尝试使用' -tt '命令行选项运行脚本,以确定何时意外混合制表符和空格。 Of course any decent editor will be able to highlight tabs versus spaces (such as Vim's 'list' option ). 当然,任何体面的编辑器都能够突出显示标签与空格(例如Vim的'list'选项 )。

The indentation is wrong, as the error tells you. 错误告诉你,缩进是错误的。 As you can see, you have indented the code beginning with the indicated line too little to be in the for loop, but too much to be at the same level as the for loop. 正如您所看到的,您已经缩减了从指示的行开始的代码太少而不能在for循环中,但是太多而不能与for循环处于同一级别。 Python sees the lack of indentation as ending the for loop, then complains you have indented the rest of the code too much. Python认为缺少缩进作为结束for循环,然后抱怨你已经过多地缩进了其余的代码。 (The def line I'm betting is just an artifact of how Stack Overflow wants you to format your code.) (我打赌的def线只是Stack Overflow希望你格式化代码的工件。)

Edit: Given your correction, I'm betting you have a mixture of tabs and spaces in the source file, such that it looks to the human eye like the code lines up, but Python considers it not to. 编辑:鉴于你的更正,我打赌你在源文件中有一个标签和空格的混合,这样它看起来就像代码排列的人眼,但Python认为它不是。 As others have suggested, using only spaces is the recommended practice (see PEP 8 ). 正如其他人所建议的那样,建议的做法是使用空格(参见PEP 8 )。 If you start Python with python -t , you will get warnings if there are mixed tabs and spaces in your code, which should help you pinpoint the issue. 如果使用python -t启动Python,如果代码中有混合选项卡和空格,则会收到警告,这可以帮助您查明问题。

The error is pretty straightforward - the line starting with check_exists_sql isn't indented properly. 错误非常简单 - 以check_exists_sql开头的行没有正确缩进。 From the context of your code, I'd indent it and the following lines to match the line before it: 从代码的上下文中,我会缩进它和以下行以匹配它之前的行:

   #open db connection
   db = MySQLdb.connect("localhost","root","str0ng","TESTDB")

   #prepare a cursor object using cursor() method
   cursor = db.cursor()

   #see if any links in the DB match the crawled link
   check_exists_sql = "SELECT * FROM LINKS WHERE link = '%s' LIMIT 1" % item['link']

   cursor.execute(check_exists_sql)

And keep indenting it until the for loop ends (all the way through to and including items.append(item) . 并保持缩进,直到for循环结束(一直到包括items.append(item)

As the error says you have not correctly indented code, check_exists_sql is not aligned with line above it cursor = db.cursor() . 由于错误显示您没有正确缩进代码,因此check_exists_sql未与其上方的行对齐cursor = db.cursor()

Also use 4 spaces for indentation. 也可以使用4个空格进行压痕。

Read this http://diveintopython.net/getting_to_know_python/indenting_code.html 阅读此http://diveintopython.net/getting_to_know_python/indenting_code.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM