在独立的抓取脚本中使用自定义中间件



我正在编写一个独立的抓取脚本(update.py(,该脚本实现了自定义下载器中间件。

该脚本当前使用的是此处和此处记录的 CrawlerProcess(( API。

它看起来像这样:

from scrapy.crawler import CrawlerProcess
import scrapy
class CustomMiddleware(object):
.... custom middleware definition
settings = {'LOG_LEVEL' :'INFO',
'COOKIES_ENABLED' : False,
'DOWNLOADER_MIDDLEWARES' : {
'update.CustomMiddleware': 400,
}
}
class CarvanaSpider(scrapy.Spider)
... Spider definition
process = CrawlerProcess(settings)
process.crawl(CarvanaSpider)
process.start()

脚本返回错误:"没有名为'update'的模块">

如果我替换更新。自定义中间件与自定义中间件,它返回"不是有效路径">

我知道 get_project_settings(( 实用程序,但我的脚本不能在项目文件夹中,并且必须能够在没有任何其他文件的情况下运行。

这是可以实现的吗?如果是,实现这一目标的最佳方法是什么?

您需要单独的中间件文件并在脚本之上导入中间件。

类自定义中间件(对象(: ....自定义中间件定义

该类将 middleware.py

在设置中只像这样添加

settings = {'LOG_LEVEL' :'INFO',
'COOKIES_ENABLED' : False,
'DOWNLOADER_MIDDLEWARES' : {
'middleware.CustomMiddleware': 400,
}
}

并且两者都 middleware.py 和您在同一个目录中编写脚本。

最新更新