繁体   English   中英

Pipeline.py显示异常

[英]Pipeline.py showing exception

我正在Scrapy中建立一个小项目,对Scrapy还是陌生的。 当我运行我的Spider时,它在我的管道中显示一个异常错误,内容为:

item ['Number'] [0],exception.IndexError:列表索引超出范围

我的管道文件:

import sys
from scrapy.utils.python import unicode_to_str
import MySQLdb
from project2.settings import MYSQL


# the Pipeline settings.
class MySQLStorePipeline(object):

    def __init__(self):
        db=MySQLdb.connect(user='root', passwd='', db='project2', host='127.0.0.1', charset = "utf8", use_unicode = True)
        self.c=db.cursor()

    def process_item(self, item, spider):
        try:
            self.c.execute("""INSERT INTO crawlerapp_directory (Catogory, Bussiness_name, Description, Number, Web_url)  
                            VALUES (%s, %s, %s, %s, %s)""",
                           (item['Catogory'][0],
                            item['Bussiness_name'][0],
                            item['Description'][0],
                            item['Number'][0],
                            item['Web_url'][0]))

        except MySQLdb.Error, e:
            print "Error %d: %s" % (e.args[0], e.args[1])
            sys.exit (1)

        return item

我的Spider可以很好地进行爬网,但是它显示上述异常错误,并且也没有将爬取的数据保存到MySQL DB中。

请指导我解决问题。

在访问第一个元素之前,请确保检查列表是否至少包含一个条目: value[0] if value

class MySQLStorePipeline(object):
    def __init__(self):
        db = MySQLdb.connect(host='127.0.0.1', user='root', passwd='',
            db='project2', charset="utf8", use_unicode=True)
        self.cursor = db.cursor()

    def process_item(self, item, spider):
        def Item(field):
            return item.get(field)[0] if item.get(field) else ''

        self.cursor.execute("""INSERT INTO crawlerapp_directory
            (Category, Business_name, Description, Number, Web_url)
            VALUES ('%s', '%s', '%s', %s, '%s')""", (
                Item('Category'),
                Item('Business_name'),
                Item('Description'),
                Item('Number'),
                Item('Web_url'),
            ))

        return item

似乎item ['Number']为空。 验证其中是否包含所需内容。

暂无
暂无

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

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