【问题标题】:signal only works in main thread: scrappy信号仅在主线程中有效:scrapy
【发布时间】:2018-10-16 12:10:47
【问题描述】:

我正在制作一个 api,它将 JsonResponse 作为我从 scrapy 中返回的文本。当我单独运行脚本时,它运行完美。但是当我尝试将scrapy脚本与python django集成时,我没有得到输出。

我想要的只是返回对请求的响应(在我的情况下是 POSTMAN POST 请求。

这是我正在尝试的代码

from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import scrapy
from scrapy.crawler import CrawlerProcess


@csrf_exempt
def some_view(request, username):
    process = CrawlerProcess({
        'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
        'LOG_ENABLED': 'false'
    })
    process_test = process.crawl(QuotesSpider)
    process.start()

    return JsonResponse({'return': process_test})


class QuotesSpider(scrapy.Spider):
    name = "quotes"

    def start_requests(self):
        urls = [
            'http://quotes.toscrape.com/random',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        return response.css('.text::text').extract_first()

我对 python 和 django 的东西非常陌生。任何形式的帮助都将不胜感激。

【问题讨论】:

  • 我不使用这些库,但希望我能在更“通用”的 Python 上有所帮助。 1-process_testprocess_test = process.crawl(QuotesSpider) 中做了什么?在 Python 中,可以不对任何东西分配返回值。 2- 我很想说试试这个类的一个实例,就像这样:process.crawl(QuotesSpider()).
  • @Guimute process_test 正在返回对我的请求的 json 响应。并将其作为一个实例对我没有多大帮助
  • 对不起,我很笨,我在阅读时确实跳过了一行......
  • 没问题,很高兴你能帮忙

标签: django python-3.x django-rest-framework scrapy scrapy-spider


【解决方案1】:

在您的代码中,process_testCrawlerProcess,而不是抓取的输出。

你需要额外的配置来让你的蜘蛛存储它的输出“somewhere”。请参阅this SO Q&A 了解如何编写自定义管道。

如果您只想同步检索和解析单个页面,最好使用requests 检索页面,并使用parsel 解析它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多