根据代码的逻辑,最后response为''的原因可能是由于在crawl()函数中,先将response定义为全局变量,然后在fallback()函数中修改了response的值。但是由于fallback()函数是在另一个进程中执行的,所以对于response的修改不会影响到crawl()函数中的response变量。

解决这个问题的方法是,将response作为fallback()函数的参数传递,并在fallback()函数中修改它的值。修改后的代码如下:

@app.route('/crawl', methods=['POST'])
def crawl():

    data = request.json
    
    queue = Queue()
    process = Process(target=fallback, args=(queue, data))
    process.start()
    result = queue.get()
    process.join()

    if result:
        raise result
    
    response = queue.get()
    
    print(f"爬虫任务完成,结果是:\n{response}")
    return response


def fallback(queue, data):
    try:
        url = data.get('url')
        if url == None:
            return 'url不能为空'
        
        configSettings(data)
            
        # 爬取深度 int 
        depth_limit = data.get('depth_limit')
        
        # 爬取资源类型 list [1:html 2:html图片 3:音频 4:视频] 没配置默认1 2
        types = data.get('types')
        
        runner = CrawlerRunner(settings=settings)
        deferred = runner.crawl(JobSpider,start_urls=[url], depth_limit=depth_limit, types=types, result_callback=result_callback, queue=queue)
        deferred.addBoth(lambda _: reactor.stop())
        reactor.run()
        queue.put(None)
    except Exception as e:
        queue.put(e)


def result_callback(result, queue):
    json_str = json.dumps(result)
    queue.put(json_str)

在修改后的代码中,将result_callback()函数的参数中添加了一个queue参数,并在函数中使用queue.put()将结果存入队列中。然后在crawl()函数中使用queue.get()获取队列中的结果赋值给response变量。这样就可以正确地获取到爬虫的结果了

approutecrawl methods=POSTdef crawl data = requestjson # url = datageturl # if url == None # return url不能为空 # configSettingsdata # # 爬取深度 int # depth_limit = data

原文地址: http://www.cveoy.top/t/topic/iRKk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录