簡體   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