Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrate Scrapy with Django : How to

I'm still very new in Django I am following this tutorial on how to integrate scrapy and django.

the problem is when i am trying to use my own spider it's just wont work. I have tried the spider outside django and it's work just fine, some help will be very helpful.

This is my spider.py file

import scrapy
from scrapy_splash import SplashRequest

class NewsSpider(scrapy.Spider):
   name = 'detik'
   allowed_domains = ['news.detik.com']
   start_urls = ['https://news.detik.com/indeks/all/?date=02/28/2018']

def parse(self, response):  
    urls = response.xpath("//div/article/a/@href").extract()        
    for url in urls:
        url = response.urljoin(url)
        yield scrapy.Request(url=url, callback=self.parse_detail)

    # follow pagination link
    page_next =   response.xpath("//a[@class = 'last']/@href").extract_first()
    if page_next:
        page_next = response.urljoin(page_next)
        yield scrapy.Request(url=page_next, callback=self.parse)

def parse_detail(self,response):
    x = {}
    x['breadcrumbs'] = response.xpath("//div[@class='breadcrumb']/a/text()").extract(),
    x['tanggal'] = response.xpath("//div[@class='date']/text()").extract_first(),
    x['penulis'] = response.xpath("//div[@class='author']/text()").extract_first(),
    x['judul'] = response.xpath("//h1/text()").extract_first(),
    x['berita'] = response.xpath("normalize-space(//div[@class='detail_text'])").extract_first(),
    x['tag'] = response.xpath("//div[@class='detail_tag']/a/text()").extract(),
    x['url'] = response.request.url,
    return x

this is my pipeline file

class DetikAppPipeline(object):

def process_item(self, item, spider):
    item = detikNewsItem()
    self.items.append(item['breadcrumbs'])
    self.items.append(item['tanggal'])
    self.items.append(item['penulis'])
    self.items.append(item['judul'])
    self.items.append(item['berita'])
    self.items.append(item['tag'])
    self.items.append(item['url'])
    item.save()

And this is the models file in django

class detikNewsItem(models.Model):
    breadcrumbs = models.TextField()
    tanggal = models.TextField()
    penulis = models.TextField()
    judul = models.TextField()
    berita = models.TextField()
    tag = models.TextField()
    url = models.TextField()

    @property
    def to_dict(self):
    data = {
        'url': json.loads(self.url),
        'tanggal': self.tanggal
    }
    return data

    def __str__(self):
        return self.url
like image 722
Vira Xeva Avatar asked Jun 01 '18 07:06

Vira Xeva


1 Answers

It's example how to write Scrapy pileline in Django project.

from <YOU_APP_NAME>.models import detikNewsItem

class DetikAppPipeline(object):
    def process_item(self, item, spider):
        d, created = detikNewsItem.objects.get_or_create(breadcrumbs=item['breadcrumbs'], url=item['url'])
        if created:        
            d.tanggal = item['tanggal']
            d.penulis = item['penulis']
            d.judul = item['judul']
            d.berita = item['berita']
            d.tag = item['tag']
            d.save()
        
        return item

By the way you need to run Scrapy in Django environment. There are several ways to do that:

  1. Using django-extensions module. Need to create new file:

    <DJANG_PROJECT>/scripts/__init__.py <DJANG_PROJECT>/scripts/run_scrapy.py

With code inside:

from scrapy.cmdline import execute

execute(['run_scrapy.py', 'crawl', 'detik'])
  1. Another way is to use Django Managment. Need to create folders in project with file:

    <folder_of_app>/management/commands/__init__.py <folder_of_app>/management/commands/scrapy.py scrapy.py file should contain code:

    from scrapy.cmdline import execute
    
    from django.core.management.base import BaseCommand
    
    class Command(BaseCommand):
        help = 'Run scrapy.'
    
        def add_arguments(self, parser):
            parser.add_argument('arguments', nargs='+', type=str)
    
        def handle(self, *args, **options):
            args = []
            args.append('scrapy.py')
            args.extend(options['arguments'])
            execute(args)
    

It allow to run Scrapy in Django environment like this:

python manage.py scrapy crawl detik
python manage.py scrapy shell 'https://news.detik.com/indeks/all/?date=02/28/2018'
like image 62
Oleg T. Avatar answered Oct 26 '22 07:10

Oleg T.