python - scrapy 引发异常从项目目录外部运行

标签 python scrapy

我在以下目录中有一个 scrapy 项目“教程

C:\wamp64\www\tutorial>

项目目录结构如下。

enter image description here

我想通过我的自定义 python 脚本运行蜘蛛 runspiders.py

from __future__ import print_function
  import scrapy
  from scrapy.crawler import CrawlerProcess
  from scrapy.utils.project import get_project_settings


  def main():
      process = CrawlerProcess(get_project_settings())
      process.crawl("quotes")
      process.start()

  if __name__ == '__main__' : main()

当自定义 python 脚本从 scrapy 项目文件夹中运行时,蜘蛛会正确运行

C:\wamp64\www\tutorial>python runningpiders.py

但是当自定义 python 脚本从项目文件夹外部运行时,scrapy 会引发以下异常,例如

C:\wamp64\www>python 教程/runspiders.py

File "C:\Python27\lib\site-packages\scrapy\spiderloader.py", line 43, in load
raise KeyError("Spider not found: {}".format(spider_name))
KeyError: 'Spider not found: quotes'

最佳答案

Scrapy 蜘蛛只是 Python 类(scrapy.Spider 的子类),因此您的脚本需要知道在哪里可以找到这些类,就像您在脚本中使用的任何其他 Python 类或模块一样。

在 Scrapy 项目中,您有一个 scrapy.cfg 文件,它至少做了一件事:它告诉框架在哪里可以找到项目设置。对于教程项目,它是 tutorial.settings

在设置中,Scrapy 希望有 SPIDER_MODULES 告诉它哪些模块包含蜘蛛类。对于本教程,这是 tutorial.spiders

在项目内运行脚本时,get_project_settings() 会为您完成所有这些工作,以发现设置模块并读取 SPIDER_MODULES,因为有一个 scrapy .cfg 文件。

tutorial/ 文件夹之外,您没有 scrapy.cfg。而且您的 Python 脚本也可能不知道 tutorial.spiders 的含义。

首先,您可以将 /path/to/tutorial/tutorial 添加到您的 Python path 中这样 importtutorial.spiders 就会有意义。

但是您也不需要依赖 get_project_settings() 因为您不在 Scrapy 项目文件夹中。但是您可以更改为

    process = CrawlerProcess({'SPIDER_MODULES': 'tutorial.spiders'})

(前提是您已更新 Python 路径)

另一种研究方法是使用 scrapy runspider /path/to/spider/module.py这不需要 Scrapy 项目。

您可能还想阅读configuration options (与系统其他位置的 scrapy.cfg 文件)或关于 Scrapy project structure .

关于python - scrapy 引发异常从项目目录外部运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41147350/

相关文章:

python - 如何在有约束的 scipy 中使用最小化函数

python - 自定义 distutils 命令

python - 无法使用包含空格和连字符的类名使用scrapy提取数据

python - 使用 Scrapy 而非 Scraped Items 从表中抓取数据

python-2.7 - 如何使用笔记本执行scrapy shell "URL"

python - 正则表达式结果为无

python - 如何从 NumPy 矩阵中的列而不是行中减去?

python - Scrapy 从选择器列表中返回单个项目

python - Python3.6 的 virtualenv 上没有名为 '_sqlite3' 的模块

python - Django.db 导入错误