按照路径加载类

scrapy.utils.misc.load_object

  1. from importlib import import_module
  2. def load_object(path):
  3. """Load an object given its absolute object path, and return it.
  4. object can be the import path of a class, function, variable or an
  5. instance, e.g. 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware'
  6. """
  7. try:
  8. dot = path.rindex('.')
  9. except ValueError:
  10. raise ValueError("Error loading object '%s': not a full path" % path)
  11. module, name = path[:dot], path[dot + 1:]
  12. mod = import_module(module)
  13. try:
  14. obj = getattr(mod, name)
  15. except AttributeError:
  16. raise NameError("Module '%s' doesn't define any object named '%s'" % (module, name))
  17. return obj

image.png