Pythonを使ってYahoo!ニューストピックスをターミナルに表示する 、という事をやってみます。
このPythonプログラムは、仕事中にブラウザ以外でニュース情報を見ることは出来ないか という不謹慎な理由で考えたものです。
という訳で、Pythonのスクレイピングの悪い例 として御覧ください。
Pythonとスクレイピングするためのライブラリbeautifulsoup4を使います。
ヤフーニューストピックスのサイトは常に情報が更新されている以下のRSSサイトを使います。
Yahoo!ニュース
Yahoo!ニュースは、新聞・通信社が配信するニュースのほか、映像、雑誌や個人の書き手が執筆する記事など多種多様なニュースを掲載しています。
実際に上記のサイトから得られる文字データは例としてこんな感じです。
3
<title>Yahoo!ニュース・トピックス - 主要</title>
4
<link>https://news.yahoo.co.jp/</link>
5
<description>Yahoo! JAPANのニュース・トピックスで取り上げている最新の見出しを提供しています。</description><language>ja</language><pubDate>Sun, 06 Jan 2019 21:59:42 +0900</pubDate>
7
<title>照射問題 韓国艦艇は警告せず</title>
8
<link>https://news.yahoo.co.jp/pickup/6309220</link>
9
<pubDate>Sun, 06 Jan 2019 21:55:43 +0900</pubDate>
10
<enclosure length="133" url="https://s.yimg.jp/images/icon/photo.gif" type="image/gif"></enclosure>
11
<guid isPermaLink="false">yahoo/news/topics/6309220</guid>
14
<title>入学願書の性別欄 廃止広がる</title>
15
<link>https://news.yahoo.co.jp/pickup/6309214</link>
16
<pubDate>Sun, 06 Jan 2019 20:20:01 +0900</pubDate>
17
<enclosure length="133" url="https://s.yimg.jp/images/icon/photo.gif" type="image/gif">
19
<guid isPermaLink="false">yahoo/news/topics/6309214</guid>
22
<title>ゴーン容疑者息子 仏紙に語る</title>
23
<link>https://news.yahoo.co.jp/pickup/6309216</link>
24
<pubDate>Sun, 06 Jan 2019 21:20:12 +0900</pubDate>
25
<enclosure length="133" url="https://s.yimg.jp/images/icon/photo.gif" type="image/gif">
27
<guid isPermaLink="false">yahoo/news/topics/6309216</guid>
このデータを見るとtitleタグで囲まれた部分がニューストピックス だと分かります。
これをbeautifulsoup4を使って取り出します。
まず、以下の2つをインポートしておきます。
2
from
bs4
import
BeautifulSoup
URLさえ分かっていればそのサイトのHTML情報は、urllib.request.urlopen関数 で簡単に取り出せます。
2
url
=
"https://news.yahoo.co.jp/pickup/rss.xml"
3
response
=
urllib.request.urlopen(url)
あとは、beautifulsoup4 を使ってタグ内の文字列を取得するだけです。
2
html
=
BeautifulSoup(response,
'html.parser'
)
今回のようにtitleタグが複数あるような場合、find_all を使って取り出します。find_allの引数はタグ名。
取得したデータ(変数topics)はリスト形式 となります。
2
topics
=
html.find_all(
"title"
)
あとはfor文などでリストデータを取り出すわけですが、そのまま取り出すとタグ部分も取得されてしまいます。
例:
<title>入学願書の性別欄 廃止広がる</title>
ですので実際は、変数のあとに.stringをつけてタグの中身だけ を取り出します。
ソースコード全体
checkYahooNews.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*-
"""
Yahoo!ニューストピックスをチェックして表示する
"""
import urllib.request
from bs4 import BeautifulSoup
# ニュースサイトを開く
url = "https://news.yahoo.co.jp/pickup/rss.xml"
response = urllib.request.urlopen(url)
# HTMLを解析して取得
html = BeautifulSoup(response, 'html.parser')
# トピックスの部分を取得
topics = html.find_all("title")
# ニュース情報を取得
i = 0
for item in topics:
if i > 0:
print(" {0}: {1}".format(i, item.string)) # ニュースは番号付きで表示
else:
print(item.string) # 最初のデータはニュースではなくタイトル
i+=1
実行イメージ
コメント