【问题标题】:Sending e-mail after scrape in scrapy在scrapy中刮擦后发送电子邮件
【发布时间】:2018-10-13 15:44:05
【问题描述】:

pipeline.py 代码

class Examplepipeline(object):

    def __init__(self):
        dispatcher.connect(self.spider_opened, signal=signals.spider_opened)
        dispatcher.connect(self.spider_closed, signal=signals.spider_closed)

    def spider_opened(self, spider):
        log.msg("opened spider  %s at time %s" % (spider.name,datetime.now().strftime('%H-%M-%S')))

    def process_item(self, item, spider):
            log.msg("Processsing item " + item['title'], level=log.DEBUG)


    def spider_closed(self, spider):
        log.msg("closed spider %s at %s" % (spider.name,datetime.now().strftime('%H-%M-%S')))

在上面的爬虫代码中,会显示爬虫的开始时间和结束时间,但是现在爬虫完成后,我想收到来自scrapy的“爬取完成”的邮件。是否有可能做到这一点。如果可能的话,我们可以在 spider_closed 方法中编写该代码,任何人都可以分享一些有关如何执行此操作的示例代码。

【问题讨论】:

    标签: python email scrapy


    【解决方案1】:

    您是否查看过文档:

    http://doc.scrapy.org/en/latest/topics/email.html

    文档中的基本用法

    from scrapy.mail import MailSender
    
    mailer = MailSender()
    mailer.send(to=["someone@example.com"], subject="Some subject", body="Some body", cc=["another@example.com"])
    

    您也可以自己实现一些自定义。例如,如果您想使用 gmail:

    def send_mail(self, message, title):
        print "Sending mail..........."
        import smtplib
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEText import MIMEText
        gmailUser = 'mail_you_send_from@gmail.com'
        gmailPassword = 'password'
        recipient = 'mail_to_send_to'
    
        msg = MIMEMultipart()
        msg['From'] = gmailUser
        msg['To'] = recipient
        msg['Subject'] = title
        msg.attach(MIMEText(message))
    
        mailServer = smtplib.SMTP('smtp.gmail.com', 587)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(gmailUser, gmailPassword)
        mailServer.sendmail(gmailUser, recipient, msg.as_string())
        mailServer.close()
        print "Mail sent"
    

    然后就这样称呼它:

    send_mail("some message", "Scraper Report")
    

    【讨论】:

    • 感谢您的回复,这真的很有帮助
    • 你好,有人能告诉我这些代码放在哪里吗? pipeline.py 或主侧边文件。我没有想法。谢谢
    • @user2492364 没有具体的答案,这取决于你的业务逻辑。例如,如果您想发送报告,您可以在管道上执行此操作,但我更愿意捕获蜘蛛关闭信号然后发送邮件
    【解决方案2】:

    对于自我推销,我深表歉意,但我最近创建了 yagmail:一个努力使发送 gmail 消息(文本、html、图像等)变得容易的包。

    这是您需要连接的代码:

    import yagmail
    yag = yagmail.SMTP('mail_you_send_from@gmail.com', 'password')
    

    然后你用它来发送电子邮件:

    yag.send('mail_to_send_to', 'Scraper Report', 'some message')
    

    很好的是,您不必将设置保留为文本,但您可以依靠操作系统的密钥环来获得真正安全和舒适的感觉。

    它甚至可以是单线(自动关闭):

    SMTP('mail_you_send_from').send('mail_to_send_to', 'Scraper Report', 'some message')
    

    【讨论】:

      猜你喜欢
      • 2019-10-18
      • 2011-09-13
      • 2017-04-29
      • 2012-04-16
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 2013-10-01
      • 2022-01-02
      相关资源
      最近更新 更多