【发布时间】: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 MySQLdb和import 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