LoginSignup
0
0

More than 1 year has passed since last update.

小さなDX①:python BeautifulSoupでニュースのトピックスを表示

Posted at

ニュースのトピックス一覧をすぐに表示させ、毎日のクリック回数を減らす

プログラミングでyahooニュースのトピックス一覧のタイトルとそのURLを表示することで、日々のニュースサイトを開くクリック作業を減らす

コードの流れ

① import
② ニューストピックスのURLの指定
③ 指定したURLページのhtmlデータを取得
④ 欲しいデータの取得(タイトルとそのURL)

① import

import
from bs4 import BeautifulSoup
import requests

② ニューストピックスのURLの指定

URL指定
#取得したいデータが異なる場合は変更
url = "https://news.yahoo.co.jp/topics/top-picks"

③指定したURLページのhtmlデータを取得

BeautifulSoup
response = requests.get(url)
soup = BeautifulSoup(response.content,'html.parser')

④欲しいデータの取得(タイトルとそのURL)

htmlテキスト、リンクデータ取得
#欲しいタイトルはclassを指定して取得
#.textで文字列を取得
topic = soup.find_all(class_="newsFeed_item_title")
topics = [i.text for i in topic]

#欲しいリンク先はclassを指定して取得
#.get("href")でリンク先のURLを取得
link = soup.find_all(class_="newsFeed_item_link")
links = [i.get("href") for i in link]

#printでタイトルとリンクを出力
#見やすさは個別で調整(printの出力結果)
for i in range(len(topics)):
    print(topics[i],"     ",links[i])
    print("")

参考:find_all()の使い方
https://gammasoft.jp/blog/difference-find-and-select-in-beautiful-soup-of-python/

効率化としては小さいですが、ニュースサイトを開いてそのままネットサーフィンに興じる可能性が少し減り、勉強などに使える時間が増えるのではと考えてます。
小さなDX①でした。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0