在 Scrapy 项目中使用 Django 的模型(在管道中)

Use Django's models in a Scrapy project (in the pipeline)

之前有人问过这个问题,但总是出现的答案是使用 DjangoItem。但是它在 github 上声明:

often not a good choice for a write intensive applications (such as a web crawler) ... may not scale well

这是我的问题的症结所在,我想以与 运行 [= 时相同的方式使用我的 django 模型并与之交互33=] manage.py shell 我做 from myapp.models import Model1。使用查询 like seen here.

我已经尝试过相对导入并将我的整个 scrapy 项目移动到我的 django 应用程序中,但都无济于事。

我应该把我的 scrapy 项目移到哪里才能让它工作?如何在 scrapy 管道内的 shell 中重新创建/使用所有可用的方法?

提前致谢。

在这里,我创建了一个在 django 中使用 scrapy 的示例项目。并在其中一个管道中使用 Django 模型和 ORM。

https://github.com/bipul21/scrapy_django

目录结构从您的 django 项目开始。 在这种情况下,项目名称是 django_project。 进入基础项目后,您可以在此处创建您的 scrapy 项目,即 scrapy_project

在您的 scrapy 项目设置中添加以下行以设置初始化 django

import os
import sys
import django

sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".."))
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_project.settings'

django.setup()

在管道中,我对问题模型进行了简单查询

from questions.models import Questions

class ScrapyProjectPipeline(object):
    def process_item(self, item, spider):
        try:
            question = Questions.objects.get(identifier=item["identifier"])
            print "Question already exist"
            return item
        except Questions.DoesNotExist:
            pass

        question = Questions()
        question.identifier = item["identifier"]
        question.title = item["title"]
        question.url = item["url"]
        question.save()
        return item

您可以签入项目以了解更多详细信息,例如模型架构。