2017-01-02 131 views

回答

1

您絕對可以發送電子郵件Scrapyjinja2。我們一直都在從我們的刮板提醒。我們使用mandrill發送我們的電子郵件,但您可以使用其他任何SMTP提供商發送您的電子郵件。你也可以擴展這個代碼來實現premailer到模板中。

import requests 
from scrapy import signals 
from jinja2 import Environment, PackageLoader 

class EmailExt(object): 
    """ 
    Email extension for scrapy 
    """ 

    @classmethod 
    def from_crawler(cls, crawler): 
     """ 
     On `spider_closed` signal call `self.spider_closed()` 
     """ 
     ext = cls() 
     crawler.signals.connect(ext.spider_closed, 
           signal=signals.spider_closed) 
     return ext 

    def spider_closed(self, spider, reason): 

     #initialize `PackageLoader` with the directory to look for HTML templates 
     env = Environment(loader=PackageLoader('templates', 'emails')) 

     template = env.get_template("email-template.html") 

     # render template with the custom variables in your jinja2 template 
     html = template.render(title="Email from scraper", count=10) 

     # send the email using the mandrill API 
     requests.post('https://api.mailgun.net/v3/yourcompany/messages', 
         auth=('api', 'API-KEY-FOR-MANDRILL'), 
         data={'from': '[email protected]', 
          'to': '[email protected]', 
          'subject': 'Email from scraper', 
          'html': html}) 
相關問題