Python Pipeline.py显示异常
我正在Scrapy建立一个小项目,我是Scrapy的新手。 当我运行spider时,它在我的管道中显示一个异常错误,该错误表示: 项['Number'][0],异常。索引器错误:列表索引超出范围 我的管道文件:Python Pipeline.py显示异常,python,mysql,web-scraping,scrapy,mysql-python,Python,Mysql,Web Scraping,Scrapy,Mysql Python,我正在Scrapy建立一个小项目,我是Scrapy的新手。 当我运行spider时,它在我的管道中显示一个异常错误,该错误表示: 项['Number'][0],异常。索引器错误:列表索引超出范围 我的管道文件: import sys from scrapy.utils.python import unicode_to_str import MySQLdb from project2.settings import MYSQL # the Pipeline settings. class My
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数据库中
请指导我解决问题。项['Number']似乎为空。验证它是否包含所需内容。在访问第一个元素之前,请确保检查列表是否包含至少一个条目:
value[0],如果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
在number中,我试图存储所刮取数据的电话号码。正如u所说,它可能是空的,我尝试在没有属性number的情况下运行spider,spider运行正常,无错误,但它没有保存正在刮取的其余数据。