2020年3月21日土曜日

開発環境

退屈なことはPythonにやらせよう ―ノンプログラマーにもできる自動化処理プログラミング (Al Sweigart(著)、相川 愛三(翻訳)、オライリージャパン)の第Ⅱ部(処理の自動化)、16章(電子メールやSMSの送信)、16.9(演習プロジェクト)、16.9.2(傘のリマインダー )の解答を求めてみる。

コード

#!/usr/bin/env python3
# twilioのアカウントを取得してないから、代わりに自分自身のメールへ送信
import config
import smtplib
import requests
import bs4

url: str = 'https://weather.yahoo.co.jp/weather/jp/13/4410.html'
res = requests.get(url)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, features='lxml')
weather: str = soup.select('.forecastCity .pict')[0].text
if '雨' in weather:
    smtp_obj = smtplib.SMTP('smtp.example.com', 587)
    smtp_obj.ehlo()
    smtp_obj.starttls()
    smtp_obj.login(config.my_email, config.my_password)
    smtp_obj.sendmail(config.my_email, config.my_email,
                      f'Subject: 天気\n{weather}')
    smtp_obj.quit()
else:
    print(f'今日は傘はいらない。天気 {weather}')

入出力結果(Zsh、PowerShell、Terminal、Jupyter(IPython))

% ./sample2.py
今日は傘はいらない。天気 晴れ
%

0 コメント:

コメントを投稿