在使用 Scrapy 和 MySQLdb 进行网络爬取和数据存储时,可能遇到以下问题:
- 在 Mac OS X Lion 10.7.5 系统中,使用 pip 安装 MySQLdb 存在兼容性问题,导致无法导入 MySQLdb 模块。
- 在 Wing IDE 中切换到 Macports 版本的 Python 后,虽然可以在 Python 交互式命令行中导入 MySQLdb,但使用 Scrapy 进行网络爬取时,仍然出现找不到 MySQLdb 模块的错误。
2. 解决方案
2.1 安装 Macports
首先,需要安装 Macports 包管理工具。Macports 是一个开源软件包管理系统,可以帮助用户轻松安装各种软件。具体步骤如下:
- 打开终端,输入以下命令:
sudo port install MacPortsBase
- 按照提示完成安装过程。
2.2 安装 MySQL 和 MySQL-python (MySQLdb)
安装 Macports 后,即可使用它来安装 MySQL 和 MySQL-python (MySQLdb) 模块。具体步骤如下:
- 打开终端,输入以下命令:
sudo port install mysql56-server
- 安装 MySQL-python (MySQLdb) 模块:
sudo port install py27-mysql
2.3 配置 Scrapy 使用 Macports 版本的 Python
在 Wing IDE 中,需要将 Scrapy 配置为使用 Macports 版本的 Python。具体步骤如下:
- 打开 Wing IDE,点击“Preferences”菜单。
- 在弹出窗口中,选择“Python”选项卡。
- 在“Interpreter”字段中,选择 Macports 版本的 Python,例如:
/opt/local/bin/python2.7
- 点击“OK”按钮保存设置。
2.4 解决 Scrapy 导入 MySQLdb 模块的错误
在解决完上述问题后,仍然可能遇到 Scrapy 无法导入 MySQLdb 模块的错误。此时,需要将 MySQLdb 模块的路径添加到 Scrapy 的 PYTHONPATH 环境变量中。具体步骤如下:
- 打开终端,输入以下命令:
export PYTHONPATH="/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages:$PYTHONPATH"
- 重新启动 Scrapy,确认是否能够正常导入 MySQLdb 模块。
2.5 示例代码
以下是一个使用 Scrapy 和 MySQLdb 进行网络爬取和数据存储的示例代码:
from scrapy import log
from twisted.enterprise import adbapi
import time
import MySQLdb.cursors
class BoxofficemojoPipeline(object):
def __init__(self):
print('init')
self.dbpool = adbapi.ConnectionPool('MySQLdb', db='testdb', user='testuser', passwd='test', cursorclass=MySQLdb.cursors.DictCursor, charset='utf8', use_unicode=True)
def process_item(self, item, spider):
print('process')
query = self.dbpool.runInteraction(self._conditional_insert, item) # ("""INSERT INTO Example_Movie (title, url, gross, release) VALUES (%s, %s, %s, %s)""", (item['title'].endcode('utf-8'), item['url'].encode('utf-8'), item['gross'].encode('utf-8'), item['release'].encode('utf-8')))
query.addErrback(self.handle_error) # self.conn.commit()
return item
def _conditional_insert(self, tx, item):
print('conditional insert')
# Create record if doesn't exist
# all this block run on it's own thread
tx.execute("select * from example_movie where url = %s", (item['url'], ))
result = tx.fetchone()
if result:
log.msg("Item already stored in db: %s" % item, level=log.DEBUG)
else:
tx.execute("insert into example_movie (title, url, gross, release) values (%s, %s, %s, %s)", (item['title'].encode('utf-8'), item['url'].encode('utf-8'), item['gross'].encode('utf-8'), item['release'].encode('utf-8')))
log.msg("Item stored in db: %s" % item, level=log.DEBUG)
def handle_error(self, e):
print('handle_error')
log.err(e)
希望以上解决方案能帮助您解决 Scrapy and MySQLdb 在 Mac OS X Lion 系统中的兼容性问题。