【问题标题】:How to run scrapy spider with celery如何用芹菜运行爬虫
【发布时间】:2021-05-12 11:33:49
【问题描述】:

我正在尝试运行一个scrapy spider,它需要一些参数并使用os.system 运行它。但是 celery 任务(scraper)在完成之前不会被执行。

蜘蛛

class SpecificAuthorQuotesSpider(scrapy.Spider):
    """Extracts the quotes from specific author"""

    start_urls = ['https://quotes.toscrape.com/']

    name = "some-quotes"

    def __init__(self, author=None, **kwargs):
        self.author = author
        super().__init__(**kwargs)

    def parse(self, response, **kwargs):
        item = QuotesItem()

        all_div_quotes = response.css('div.quote')
        for quote in all_div_quotes:
            title = quote.css('span.text::text').extract_first().replace('”', '').replace("“", "")
            author = quote.css('.author::text').extract_first()

            # Check if author's name matches
            if author.strip().lower() == self.author.strip().lower():
                item['text'] = title
                item['author'] = author
                yield item

        # Crawl Next Page
        next_page = response.css('li.next a::attr(href)').get()
        if next_page is not None:
            yield response.follow(next_page, callback=self.parse)

任务

@shared_task
def task_scrape_from_author(author_name):
    """Scrape quotes from author"""
    django_path = Path(__file__).resolve().parent.parent
    os.chdir(str(django_path)+"/scraper")
    os.system(
        "scrapy crawl some-quotes -a author='{}'".format(author_name))

查看

def scrape_quotes_from_author(request):
    if request.user.is_superuser:
        author_name = request.POST.get("athr_name")
        task_scrape_from_author.delay(author_name)
        messages.add_message(
            request, messages.INFO, 'Started crawling quotes from {}'.format(author_name))
        return HttpResponseRedirect(reverse("admin:index"))
    else:
        return HttpResponseRedirect("../")

Github Repo

我不明白为什么在没有任何消息的情况下任务没有完成和中断。我也尝试设置最大超时,但没有奏效。

【问题讨论】:

  • 我遇到了与 Django + Scrapy 项目相同的问题。我用 Crawler runner 解决了这个问题。
  • 能否提供一些参考。
  • 我们会弄清楚的。我正在使用相同的系统。我回答这个问题。

标签: django scrapy celery


【解决方案1】:

我为 spider_name 和 spider_class 制作了一个表格。

模型.py

class Spiders(models.Model):
    spider_class = models.CharField(max_length=50,verbose_name="Spider Class",null=True)
    spider_name = models.CharField(max_length=50,verbose_name="Spider Name",null=True)

我在这里收集所有的 spider_name 和 class'。

view.py

from .model import Spiders
from spider_dir.start import startallSpiders

def runAllspiders(request):
    all_class = []
    spiders = Spiders.objects.all()
    for spider in spiders:
        spider_name = spider.spider_name
        name = 'spider_dir.spider_dir.spiders.'+spider_name
        i = importlib.import_module(name)
        class_ = getattr(i, spider.spider_class)
        all_class.append(class_)
    try:
        startallSpiders(all_class)
        messages.success(request,"Spiders works fine")
    except:
        messages.warning(request,"An error occure")
    
    return redirect(request.META['HTTP_REFERER'])

我在scrapy dir中做了一个启动py

我用钩针一次性启动所有蜘蛛。

start.py

from .spider_dir import settings as st
from scrapy.settings import Settings
from crochet import setup
setup()

def startallSpiders(all_Class):
    for class_ in all_Class:
        crawler_settings = Settings()
        setup()
        crawler_settings.setmodule(st)
        runner= CrawlerRunner(settings=crawler_settings)
        runner.crawl(class_)

settings.py 你必须在 scrapy 设置中附加 Django 设置。

import os,sys
sys.path.append(os.path.dirname(os.path.abspath('.')))
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_project.settings'
import django
django.setup()

我与 Crawlerrunner 合作,6 个月内一切正常。

【讨论】:

    猜你喜欢
    • 2020-09-27
    • 2014-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多