python - scrapy的异常处理一般怎么做?
巴扎黑
巴扎黑 2017-04-17 17:50:26
[Python讨论组]

发现在运行过程中有少量的请求有异常,或者请求响应了404 500之类的,又或者代码本身运行抛异常, 怎么记录这些异常呢。

巴扎黑
巴扎黑

全部回复(3)
巴扎黑

我目前的做法是用下载中间件去捕捉失败的请求,仅供大家参考

class CustomFaillogMiddleware(object):

    @classmethod
    def from_crawler(cls, crawler):
        return cls()

    def process_response(self, request, response, spider):
        if response.status >= 400:
            reason = response_status_message(response.status)
            self._faillog(request, u'HTTPERROR',reason, spider)
        return response

    def process_exception(self, request, exception, spider):
        self._faillog(request, u'EXCEPTION', exception, spider)
        return request

    def _faillog(self, request, errorType, reason, spider):
        with codecs.open('log/faillog.log', 'a', encoding='utf-8') as file:
            file.write("%(now)s [%(error)s] %(url)s reason: %(reason)s \r\n" %
                       {'now':datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                        'error': errorType,
                        'url': request.url,
                        'reason': reason})
迷茫

你是想通过log的方式来记录异常吗? Scrapy提供了log功能的

ringa_lee

http://scrapy-chs.readthedocs.io/zh_CN/1.0/topics/logging.html

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号