我正在尝试将多个spider的结果存储到MySQL中不同的表中

2024-06-16 08:27:32 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的管道.py. 我有两只蜘蛛一只叫布里斯托尔.py还有一个巴斯.py. 当我运行'scrapy crawl bristol'时,它会自动将结果添加到名为'bristol'的MySQL数据库表中。我想运行'srapy crawl bath',并能够将结果存储在MySQL数据库的表名'bath'下。我尝试为“Bristol”表添加完全相同的代码行,但收到一个错误。这是我试着直接放在第一个下面的代码self.cursor.execute执行你知道吗

self.cursor.execute("""INSERT INTO Bath(BathCountry, BathQualification) VALUES ('{0}', '{1}')""".format(item['BathCountry'], "".join([s.encode('utf8') for s in item['BathQualification']])))

当我尝试这个我收到一个错误,有没有办法做到这一点?这就是错误

 exceptions.KeyError: 'BathCountry'

提前谢谢你的帮助。你知道吗

import sys
import MySQLdb
import MySQLdb.cursors
import hashlib
from scrapy.exceptions import DropItem
from scrapy.http import Request

class TestPipeline(object):

    def __init__(self):
        self.conn = MySQLdb.connect(
            user='user',
            passwd='password',
            db='db',
            host='host',
            charset='utf8',
            use_unicode=True
            )
        self.cursor = self.conn.cursor()

    def process_item(self, item, spider):
        try:
            self.cursor.execute("""INSERT INTO Bristol(BristolCountry, BristolQualification) VALUES ('{0}', '{1}')""".format(item['BristolCountry'], "".join([s.encode('utf8') for s in item['BristolQualification']])))
            self.conn.commit()
            return item

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

Tags: pyimportselfexecute错误mysqlutf8conn