【Python】Twitterに今日のおすすめ記事をツイートする
機能
Twitterに今日のおすすめ記事をツイートするPythonプログラムです。
ブログの記事一覧からランダムで記事を選択して、Twitterにツイートします。
- 記事一覧
- 実行結果
サンプル動画
プログラム
#! Python3 # 機能 # 今日のおすすめ記事をツイートする # 使い方 # 1.Pythonを実行する # 実行コマンド # python blog_twitter.py import os import sys import bs4 import requests import random sys.path.append(os.path.abspath("..")) from tweet_bot import tweet_bot DOMAIN = "https://stmtk358.hatenablog.com/" LIST_PAGE_PATH = "entry/2021/07/23/091937" # ブログのURL一覧を取得する def get_blog_urls(): # 一覧ページ取得 res = requests.get(DOMAIN + LIST_PAGE_PATH) res.raise_for_status() # リンク取得 soup = bs4.BeautifulSoup(res.text, "lxml") links = soup.select(".entry-content a") # 記事のURL取得 urls = [] for link in links: url = link.get("href") if not url: continue if not url.startswith(DOMAIN): continue urls.append(url) return urls # ランダムに記事を選んで、ツイートする url = random.choice(get_blog_urls()) message = "今日のオススメ記事\n" + url tweet_bot.tweet(message)
ツイートには以下で作成したモジュールを使用しています。
注意点として、Pythonは実行ファイルがあるフォルダ配下にしかパスが通らないようです。
私の環境ではプログラムごとにフォルダを分けているため、blog_twitter.pyを実行する際にtweet_bot.pyが参照できません。
..\Python\sns\blog_twitter\blog_twitter.py ..\Python\sns\tweet_bot\tweet_bot.py
この問題を回避するため、sys.pathにsnsフォルダ(..)を追加して、tweet_botフォルダ配下も参照できるようにしています。
sys.path.append(os.path.abspath("..")) from sns.tweet_bot import tweet_bot
使い方
- Pythonを実行する
実行コマンド
python blog_twitter.py
requestsとbs4をインストールしていない場合は以下のコマンドでインストールして下さい。
pip install requests pip install beautifulsoup4