发布于 2年前

Scrapy发送邮件 报错 builtins.AttributeError: 'NoneType' object has no attribute 'bio_read'

应用场景:在爬虫关闭或者爬虫空闲时可以通过发送邮件的提醒,通过twisted的非阻塞IO实现,可以直接写在spider中,也可以写在中间件或者扩展中,看你具体的需求。

看下面的示例代码前,先看下官网,熟悉基本的属性。

官网地址 sending e-mailhttps://docs.scrapy.org/en/latest/topics/email.html?highlight=MailSender

1 首先在settings同级的目录下创建extendions(扩展)文件夹,代码如下:

from scrapy import signals

from scrapy.exceptions import NotConfigured

from scrapy.mail import MailSender

import logging

logger = logging.getLogger(__name__)

class SendEmail(object):

def__init__(self,sender,crawler):

self.sender = sender

crawler.signals.connect(self.spider_idle, signal=signals.spider_idle)

crawler.signals.connect(self.spider_closed, signal=signals.spider_closed)

@classmethod

def from_crawler(cls,crawler):

if not crawler.settings.getbool('MYEXT_ENABLED'):

raise NotConfigured

mail_host = crawler.settings.get('MAIL_HOST') # 发送邮件的服务器

mail_port = crawler.settings.get('MAIL_PORT') # 邮件发送者

mail_user = crawler.settings.get('MAIL_USER') # 邮件发送者

mail_pass = crawler.settings.get('MAIL_PASS') # 发送邮箱的密码不是你注册时的密码,而是授权码!!!切记!

sender = MailSender(mail_host, mail_user, mail_user, mail_pass, mail_port) #邮发送者和邮件账户是同一个都写mail_user

h = cls(sender, crawler)

return h

def spider_idle(self,spider):

logger.info('idle spider %s' % spider.name)

def spider_closed(self, spider):

logger.info("closed spider %s", % spider.name)

body = 'spider[%s] is closed' % spider.name

subject = '[%s] good!!!' % spider.name

self.sender.send(to={'zfeijun@foxmail.com'}, subject=subject, body=body)

return self.sender.send(to={'zfeijun@foxmail.com'}, subject=subject, body=body)

这里为什么是return self.sender.send,是因为直接用sender.send会报 builtins.AttributeError: 'NoneType' object has no attribute 'bio_read'的错误(邮件会发送成功),具体原因不是很懂,有大牛知道的可以指导一下。

解决方法参考:https://github.com/scrapy/scrapy/issues/3478

在sender.send前加return就好了。

2 在扩展中写好代码后,需要在settings中启用

EXTENSIONS = {

'scrapy.extensions.telnet.TelnetConsole': 300,

'bukalapak.extendions.sendmail.SendEmail':300,

}

MYEXT_ENABLED =True

©2020 edoou.com   京ICP备16001874号-3