【问题标题】:Pipeline.py showing exceptionPipeline.py 显示异常
【发布时间】:2013-07-31 01:38:44
【问题描述】:

我正在 Scrapy 中构建一个小项目,并且是 Scrapy 的新手。 当我运行我的蜘蛛时,它在我的管道中显示一个异常错误,上面写着:

item['Number'][0], exceptions.IndexError: list index out of range

我的管道文件:

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

我的蜘蛛爬得很好,但它显示了上述异常错误,也没有将抓取的数据保存到 MySQL 数据库中。

请指导我解决问题。

【问题讨论】:

    标签: python mysql web-scraping scrapy mysql-python


    【解决方案1】:

    似乎 item['Number'] 是空的。验证它是否包含您想要的内容。

    【讨论】:

    • in number 我正在尝试存储抓取数据的电话号码
    • 你说它可能是空的,我试图在没有属性 Number 的情况下运行我的蜘蛛,蜘蛛运行良好,,没有错误,但是它没有保存它的其余数据刮。
    【解决方案2】:

    确保在访问第一个元素之前检查列表是否包含至少一个条目: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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-13
      相关资源
      最近更新 更多