且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-01 22:41:10

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

In here i have create a sample project which uses scrapy inside django. And uses Django models and ORM in the one of the pipelines.

https://github.com/bipul21/scrapy_django

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

The directory structure starts with your django project. In this case the the project name is django_project. Once inside the base project you create your scrapy project i.e. scrapy_project here

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

In your scrapy project settings add the following line to setup initialize 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()

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

In the pipeline i have made a simple query to Question Model

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

您可以在项目中签入任何更多详细信息,例如模型架构.

You can check in the project for any further details like model schema.