使用Scrapy,获取“错误:ImportError:没有名为testspiders.spiders.followall的模块”

时间:2014-10-22 15:27:03

标签: python node.js scrapy

我正在尝试从脚本运行Scrapy,并且一直在关注教程here。我遇到了一条错误消息,指出Error: ImportError: No module named testspiders.spiders.followall。我一直在寻找解决方案,但尚未找到匹配。

我实际上是通过node.js运行这个python脚本,它有一个名为python-shell的模块,它只允许你使用以下简单代码运行python脚本:

var PythonShell = require('python-shell');

PythonShell.run('my_script.py', function (err) {
  if (err) throw err;
  console.log('finished');
});

逐字,我的代码是从scrapy网站复制的:

from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from testspiders.spiders.followall import FollowAllSpider
from scrapy.utils.project import get_project_settings

spider = FollowAllSpider(domain='scrapinghub.com')
settings = get_project_settings()
crawler = Crawler(settings)
crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
crawler.configure()
crawler.crawl(spider)
crawler.start()
log.start()
reactor.run() 

我的目录结构只是通过添加python目录和文件以及使用python-shell的几行代码从express framework修改而来:

-python-node
    -bin
    -node_modules
    -public
    -python 
        -my_script.py
    -routes
    -views
    -app.js
    -package.json 

注意:如果我进入python目录并运行python my_script.py,这也不起作用,我收到相同的错误消息:ImportError: No module named testspiders.spiders.followall

1 个答案:

答案 0 :(得分:3)

在使用scrapy运行爬网程序时,会自动将路径根目录(testspiders /的父目录)添加到路径中。使用python运行脚本时,情况并非如此。你有工作目录和PATH和PYTHONPATH中定义的任何内容。

您可以使用sys.path

检查python中的当前路径

因此,要使导入语句与python一起使用,您可以:

  • 使用sys.path.append()将testspiders / parent dir添加到路径中(必须在导入testspiders ...语句之前执行此操作)
  • 将父目录添加到PYTHONPATH系统变量
  • 从testspiders /
  • 的父目录运行python命令
  • 编辑导入语句(因此它们根据您的路径工作)