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

标签 python django django-models scrapy scrapy-pipeline

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

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

这是我的问题的症结所在,我想以与运行 python manage.py shell 时相同的方式使用我的 django 模型并与其交互> 然后我执行 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 here

在您的 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

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

关于python - 在 Scrapy 项目中使用 Django 的模型(在管道中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41905464/

相关文章:

python - 基于 django 类的 View 不接受 view_args 和 view kwargs

django - Django 中复杂的 "limit_choices_to"函数

python - 从多个模型创建模型以添加到数据库?

python:分散不显示

python - 使用键参数列出排序错误

python - 由于 Django 1.2.1 'prepopulated_fields' 不会在管理中预填充

django - get_context_data 方法 Django

django - DRF - 如何让 WritableField 不将整个数据库加载到内存中?

python - 子图的 matplotlib get_color

python - 禁用日期选择器上的 Selenium 输入日期