Mike的Python學院

Scrapy、框架設計、資料處理、Python、網頁爬蟲、程式語言、程式撰寫、Python網路爬蟲、Gmail、資料擷取

Mike Ku

Learn Code With Mike品牌創辦人

2022/01/19

一定要懂的Scrapy框架結合Gmail寄送爬取資料附件秘訣

本文將爬取的結果存入CSV檔案後,透過Gmail附件郵寄給使用者。在開始之前,大家可以先參考[Python實戰應用]Python寄送Gmail電子郵件實作教學文章( https://www.learncodewithmike.com/2020/02/python-email.html )的第二節步驟,取得Gmail的應用程式密碼,以便能夠利用它的SMTP(簡易郵件傳輸協定)來發送郵件。
Q: Scrapy MailSender結合Gmail發送郵件
在Scrapy網頁爬蟲框架中,想要實作發送電子郵件的功能,可以使用內建的MailSender模組(Module),透過基本的設定即可達成。開啟Scrapy專案的settings.py設定檔,加入以下的Gmail SMTP設定:
MAIL_HOST = "smtp.gmail.com"
MAIL_PORT = 587
MAIL_FROM = "申請Gmail應用程式密碼所使用的電子郵件帳號"
MAIL_PASS = "Gmail應用程式密碼"
MAIL_TLS = True
並且,將[Scrapy教學7]教你Scrapy框架匯出CSV檔案方法提升資料處理效率文章( https://www.learncodewithmike.com/2021/01/scrapy-export-csv-files.html )中所建立的CsvPipeline資料模型管道設定開啟,如下範例:
ITEM_PIPELINES = {
'news_scraper.pipelines.CsvPipeline': 500,
}
設定完成後,開啟ITEM PIPELINE資料模型管道(pipelines.py)檔案,引用Scrapy框架的設定檔及MailSender模組(Module),如下範例:
from itemadapter import ItemAdapter
from news_scraper import settings
from scrapy.mail import MailSender
接著,在CsvPipeline類別(Class)的close_spider()方法(Method)中,來建立Scrapy MailSender物件,以及指定Gmail的附件,包含「附件顯示的名稱(attach_name)」、「網際網路媒體類型(mime_type)」及「檔案物件(file_object)」,如下範例:
class CsvPipeline:
...
def close_spider(self, spider):
self.exporter.finish_exporting()
self.file.close()
mail = MailSender(smtphost=settings.MAIL_HOST,
smtpport=settings.MAIL_PORT,
smtpuser=settings.MAIL_FROM,
smtppass=settings.MAIL_PASS,
smtptls=settings.MAIL_TLS)
attach_name = "posts.csv"
mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
file_object = open("posts.csv", "rb")
return mail.send(to=["example@gmail.com"],
subject="news",
body="",
attachs=[(attach_name, mime_type, file_object)])
如果想要學習更多的Python應用教學,歡迎前往Learn Code With Mike(https://www.learncodewithmike.com/2021/02/scrapy-sending-gmail.html
)網站觀看更多精彩內容。
2 0 270 0