Yahooニュース・アクセスランキングの見出しを取得し合成音声で読み上げる(Windows)
Yahooニュース・アクセスランキングの見出しをスクレイピングで取得し、それを合成音声で読み上げます。
pywin32(win32com)はPythonからWindowsアプリケーションを制御するためのライブラリです。win32comでWindows標準の音声合成機能Microsoft Speech API(SAPI)を制御することで任意の文章を音声合成できます。
関連記事
Yahooニュース・アクセスランキングの見出しを取得し頻出単語を調べる
環境
- windows10 home
- Anaconda 3/ jupyter notebook 6.4.6
- Python 3.8.12
- requests 2.27.1
- beautifulsoup4 4.10.0
- pywin32 303
コード
requestでYahooニュース・アクセスランキングのページを取得しBeautifulSoupで分析します。BeautifulSoupオブジェクトを見るとニュースのタイトルは classが 'newsFeed_item_title' となっていたため、そのclassを抽出し文字列に変換後 'Sapi.SpVoice' に渡して合成音声で読み上げます。読み上げ速度を少し遅くするためRate=-1としています(-10~10で設定可能)。
import requests from bs4 import BeautifulSoup as bs import win32com.client # アプリケーション'Sapi.SpVoice'をオブジェクトspeechに適用 speech = win32com.client.Dispatch('Sapi.SpVoice') # 読み上げ速度は少しゆっくり speech.Rate = -1 # Responseオブジェクトの取得 rs = requests.get('https://news.yahoo.co.jp/ranking/access?ty=t&c=c_int') # BeautifulSoupオブジェクトの取得 soup = bs(rs.text.encode(rs.encoding), 'html.parser') # class='newsFeed_item_title'のみ取得 selected_class = soup.select('.newsFeed_item_title') # タイトルを読み上げ for i in selected_class: speech.Speak(i.string)
実行結果
Yahooニュース・アクセスランキングの見出しが1位から順に合成音声で読み上げられます。
以下のサイトを参考にさせていただきました
sozorablog > 【Python初心者にオススメ】音声合成を使って好きな言葉(テキスト)をしゃべらせる(すぐにできます)