【问题标题】:scrapy + adbapi = AttributeError: 'module' object has no attribute 'DictCursor'scrapy + adbapi = AttributeError: 'module' 对象没有属性 'DictCursor'
【发布时间】:2017-08-03 12:05:15
【问题描述】:

我有一个使用项目管道设置的 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)

【问题讨论】:

  • 顺便说一句 - 我也尝试过,包括“import MySQLdb”以及“import MySQLdb.cursors”,但无济于事。
  • 这很奇怪。如果同时导入:import MySQLdbimport MySQLdb.cursors,会怎样?
  • 顺便说一句,你用的是什么mysqldb 版本?
  • 服务器版本:我的 MacBook Pro 上的 5.5.15 MySQL 社区服务器
  • 这个 MySQL-python 1.3.0 版本从何而来?来自github.com/farcepest/MySQLdb1/tree/MySQLdb-1.3的源代码?在 PyPi 上,我最多只能看到 1.2.4

标签: python scrapy


【解决方案1】:

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

你可以试试这个

从 MySQLdb.cursors 导入 DictCursor

并将 cursorClass 更改为“cursorClass=DictCursor”

它可以在我的电脑上运行,我希望它也能帮助你和其他人

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 1970-01-01
    • 2021-01-15
    • 2015-05-16
    • 1970-01-01
    • 2022-12-20
    • 2018-01-14
    • 2014-08-15
    • 2016-07-17
    相关资源
    最近更新 更多