SCRAPY:如何将数据存储到Mysql数据库中

时间:2015-09-28 16:56:34

标签: python mysql web-scraping scrapy

我在尝试将数据存储到mysql数据库时遇到scrapy问题:我收到以下错误:(screenshot here)

我在pipelines.py中的代码是

class SQLStorePipeline(object):

    def __init__(self):
        self.dbpool = adbapi.ConnectionPool('localhost', db='python',
                user='root', passwd='', cursorclass=MySQLdb.cursors.DictCursor,
                charset='utf8', use_unicode=True)

    def process_item(self, item, spider):
        # run db query in thread pool
        query = self.dbpool.runInteraction(self._conditional_insert, item)
        query.addErrback(self.handle_error)

        return item

    def _conditional_insert(self, tx, item):
        # create record if doesn't exist. 
        # all this block run on it's own thread
        tx.execute("select * from test where name = %s", (item['name'][0], ))
        result = tx.fetchone()
        if result:
            log.msg("Item already stored in db: %s" % item, level=log.DEBUG)
        else:
            tx.execute(\
                "insert into test (name, price) "
                "values (%s, %s)",
                (item['link'][0],
                 datetime.datetime.now())
            )
            log.msg("Item stored in db: %s" % item, level=log.DEBUG)

    def handle_error(self, e):
        log.err(e)

(我是从here获得的。)

我的解析课是:

def parse(self, response):
    item = DmozItem()
    item['name'] = response.xpath('//meta[@itemprop="name"]/@content').extract()[0]
    item['price'] = response.xpath('//meta[@itemprop="price"]/@content').extract()[0]
    yield item

我知道这个问题已经被问过了,但是在问这里之前我尝试了所有不同的答案,而且没有一个有效......

有人可以帮助我吗?提前谢谢!

2 个答案:

答案 0 :(得分:1)

我找到了解决方案。实际上@alecxe是对的,他的言论使我找到了解决方案。

MySQLdb根本就没有安装,原因是它的安装失败了,因为我的名字中有一个重音,而Python因此无法处理路径。

再一次,非常感谢@alecxe!

答案 1 :(得分:0)

仔细阅读错误 - 在下一行中显示IndentationError

yield item

这意味着您需要检查缩进是否一致(每个缩进4个空格):

def parse(self, response):
    item = DmozItem()
    item['name'] = response.xpath('//meta[@itemprop="name"]/@content').extract()[0]
    item['price'] = response.xpath('//meta[@itemprop="price"]/@content').extract()[0]
    yield item

如果是这种情况,请不要混合制表符和空格。