当脚本在根目录之外时,获取scrapy项目设置

您所在的位置:网站首页 python的oschdir 当脚本在根目录之外时,获取scrapy项目设置

当脚本在根目录之外时,获取scrapy项目设置

#当脚本在根目录之外时,获取scrapy项目设置| 来源: 网络整理| 查看: 265

感谢这里已经提供的一些答案,我意识到scrapy实际上并没有导入settings.py文件。我是这样修复它的。

TLDR: 确保你将'SCRAPY_SETTINGS_MODULE'变量设置为你的实际设置.py文件。我在 Scraper 的 __init__() 函数中这样做。

考虑一个具有以下结构的项目。

my_project/ main.py # Where we are running scrapy from scraper/ run_scraper.py #Call from main goes here scrapy.cfg # deploy configuration file scraper/ # project's Python module, you'll import your code from here __init__.py items.py # project items definition file pipelines.py # project pipelines file settings.py # project settings file spiders/ # a directory where you'll later put your spiders __init__.py quotes_spider.py # Contains the QuotesSpider class

基本上,命令 替换代码1】在my_project文件夹中被执行,我在外层scraper文件夹中添加了一个run_scraper.py文件,在我的root文件夹中添加了一个main.py文件,并在spiders文件夹中添加了quotes_spider.py。

我的主要文件。

from scraper.run_scraper import Scraper scraper = Scraper() scraper.run_spiders()

My run_scraper.py file:

from scraper.scraper.spiders.quotes_spider import QuotesSpider from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings import os class Scraper: def __init__(self): settings_file_path = 'scraper.scraper.settings' # The path seen from root, ie. from main.py os.environ.setdefault('SCRAPY_SETTINGS_MODULE', settings_file_path) self.process = CrawlerProcess(get_project_settings()) self.spider = QuotesSpider # The spider you want to crawl def run_spiders(self): self.process.crawl(self.spider) self.process.start() # the script will block here until the crawling is finished

另外,请注意,设置可能需要看一下,因为路径需要根据根文件夹(my_project,不是scraper)。 所以在我的例子中。

SPIDER_MODULES = ['scraper.scraper.spiders'] NEWSPIDER_MODULE = 'scraper.scraper.spiders'

并对你的所有设置变量进行重复。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3