NHKオンラインはRSSでニュースを提供している(→NHK ONEのニュースでは、RSS(Really Simple Syndication)による情報提供を実施しています。)。これを定期的に読んで,気になるニュースを通知してみよう。あらかじめ feedparser をpipで入れておく。
まずは主要ニュースのフィードを読んで各項目のタイトルを表示するだけのコード:
import feedparser
d = feedparser.parse('https://news.web.nhk/n-data/conf/na/rss/cat0.xml')
for i in d['entries']:
print(i['title'])
10分ごとに自動で読みに行って新着ニュースのタイトルを表示する:
import feedparser
import time
s = set() # 空集合
while True:
d = feedparser.parse('https://news.web.nhk/n-data/conf/na/rss/cat0.xml')
for i in d['entries']:
x = i['title']
if x not in s:
print(x)
s.add(x)
time.sleep(600) # 10分
Python で空集合は set() とすることに注意。{} では「空の辞書(dict)」になってしまう。
あとは好きなように拡張すればよい。例えば時分秒を付けてタイトルに「東京」かつ「「感染」または「コロナ」」が含まれればMacの通知センターにも通知を表示する:
import feedparser
import time
import os
from dateutil.parser import parse
s = set()
while True:
try:
d = feedparser.parse('https://news.web.nhk/n-data/conf/na/rss/cat0.xml')
except:
print("Timeout")
else:
for i in d['entries']:
x = f"{parse(i['published']):%H:%M:%S} {i['title']}"
if x not in s:
print(x)
s.add(x)
if '東京' in x and ('感染' in x or 'コロナ' in x):
x = x.replace("'", "").replace('"', '')
os.system(f"osascript -e 'display notification \"{x}\"'")
time.sleep(300)
ほかにメールやLINEを送ったりツイートしたりすることもできる。メールを送るには postfix などが動いているマシンで次のようにする:
os.system(f"echo '{x}' | mail hoge@example.com")
ちなみに,例えば三重県のニュース(旧URL https://www3.nhk.or.jp/lnews/tsu/)であれば https://news.web.nhk/lnews/tsu/toplist.xml のように最後に toplist.xml を付ければよさそうだ。