3

我有一个使用项目管道设置的 CrawlSpider,我正试图通过 MySQLdb 坚持下去。我到处搜索,发现的大多数样本至少有 6 个月大,都以相同的方式使用 adbapi。当我尝试使用相同的格式时,我收到以下错误:

AttributeError: 'module' object has no attribute 'DictCursor'

我没有看到我在这里做错了什么,但我对 Python 还很陌生,对 scrapy 也很陌生,所以完全有可能这是我忽略的简单事情。

from twisted.enterprise import adbapi
from scrapy import log

import MySQLdb.cursors

class InventoryPipeline(object):
    def __init__(self):
        self.pool = adbapi.ConnectionPool('MySQLdb',
                db='inventory',
                user='root',
                passwd='',
                cursorClass=MySQLdb.cursors.DictCursor,
                charset="utf8",
                use_unicode=True
            )


    def process_item(self, item, spider):
        query = self.pool.runInteraction(self._insert_record, item)
        query.addErrback(self._handle_error)
        return item


    def _insert_record(self, tx, item):
        tx.execute("select * from content where url = %s", (item['url']))
        result = tx.fetchone()
        if result:
            log.msg("url already in database", level=log.INFO)
        else:
            tx.execute("insert into content (url, title, link_content, main_content, header) values (%s, %s, %s, %s, %s)",
                (item['url'], item['title'], item['link_content'], item['main_content'], item['header']))
            log.msg("Item stored in db: %s" % item, level=log.INFO)
        return item


    def _handle_error(self, e):
        log.err(e)
4

1 回答 1

0

我也遇到过这个问题,我解决了。

你可以试试这个

从 MySQLdb.cursors 导入 DictCursor

并将 cursorClass 更改为“cursorClass=DictCursor”

它适用于我的电脑,我希望它也能帮助你和其他人

于 2017-08-03T04:05:15.180 回答