【问题标题】:Call a function in Settings from spider Scrapy从蜘蛛 Scrapy 调用设置中的函数
【发布时间】:2023-03-22 12:39:01
【问题描述】:

我有两个蜘蛛 AB。 我需要调用蜘蛛 settings.py 文件中定义的函数

Project Name |--Project Name | |-- spiders | | |-- __init__.py | | |-- A.py | | |-- B.py | |-- __init__.py | |-- items.py | |-- pipelines.py | |-- settings.py

settings.py中有一个函数,需要在蜘蛛关闭时从A.py和B.py访问

settings.py

def revoke_ip():
    logging.info('Revoking access')

这是我从 A.py 尝试过的:

def closed(self, reason):
    logging.info('Spider terminating because of %s' % reason)
    current_project_settings = get_project_settings()
    revoke_ip_call = getattr(current_project_settings, "revoke_ip")
    revoke_ip_call()

但这东西不起作用,here提到的也不起作用

我做错了什么或有其他方法吗?

【问题讨论】:

    标签: python scrapy


    【解决方案1】:

    导入文件时,Python 仅搜索当前目录、运行入口点脚本的目录以及包含包安装目录等位置的 sys.path。您可以导入设置文件来调用该函数。为此,请将其添加到您的函数中:

    import sys
    sys.path.insert(0, '../')
    import settings
    

    【讨论】:

    • 我如何调用撤销函数,settings.revoke()?如果我从外部project name 文件夹中以scrapy crawl A 运行爬虫,则会收到错误ImportError: No module named settings
    • 这件事部分解决了我的问题,所以我赞成答案。谢谢!
    • 如果你从其他文件夹运行你的项目,你必须指定哪个文件夹包含你想使用的模块。您可以尝试使用设置模块的绝对路径。不客气,希望对你有帮助。
    【解决方案2】:

    感谢@Jose 发布的答案,对我有用的是settings.py 与我正在运行的蜘蛛位于不同的目录中,Python 只搜索当前目录。

    所以我尝试检查每次运行蜘蛛时它提供的文件的路径,显然我得到的路径是

    /tmp/unpacked-eggs/__main__.egg/project name/spiders
    

    所以,我必须做的是:

    import sys
    import os
    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + '/../')
    import settings
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多