【Python・Tweepy】スクレイピングしたデータをTwitterAPIを使って投稿

この記事は分で読み終わります。

今回はPythonでスクレイピングしたデータをTwitterに投稿するプログラムを組みました。

ソースコード

import requests
from bs4 import BeautifulSoup
import tweepy

apiKey = 'API Key' 
apiSerect = 'API Serect'
accessToken = 'Access Token'
tokenSerect = 'Token Serect'

auth = tweepy.OAuthHandler(apiKey, apiSerect)
auth.set_access_token(accessToken, tokenSerect)
api = tweepy.API(auth)

response = requests.get('https://fich-labo.com/')
soup = BeautifulSoup(response.text, 'html.parser')
siteTitle = soup.find('title').get_text()
title = soup.find(class_="entry-title").get_text()
url = soup.find(class_="post-list__link")
tweet = siteTitle +'\n'+ title+'\n\n'+ url.get('href') +'\n'+ 'を投稿しました。'

api.update_status(tweet)
print(tweet)

APIキーやトークンなどは、Twitterのdeveloperサイトから取得してください

コンソール画面

Twitter

コード解説

まず初めに下記ライブラリ3つをダウンロードしてください。

pip install requests
pip install beautifulsoup4
pip install tweepy

ダウンロードしたライブラリをインポートしてきます。

import requests
from bs4 import BeautifulSoup
import tweepy

Twitterのdeveloperサイトから取得したAPIキーやトークンを貼り付けます。

apiKey = 'API Key' 
apiSerect = 'API Serect'
accessToken = 'Access Token'
tokenSerect = 'Token Serect'

セットしたAPIキーやトークンを一つの変数にまとめます。

auth = tweepy.OAuthHandler(apiKey, apiSerect)
auth.set_access_token(accessToken, tokenSerect)
api = tweepy.API(auth)

スクレイピングしたいサイトのURLを貼り付け、抽出したいHTMLのタグやCSSのクラスを選択します。

response = requests.get('https://fich-labo.com/')
soup = BeautifulSoup(response.text, 'html.parser')
siteTitle = soup.find('title').get_text()
title = soup.find(class_="entry-title").get_text()
url = soup.find(class_="post-list__link")
tweet = siteTitle +'\n'+ title+'\n\n'+ url.get('href') +'\n'+ 'を投稿しました。'

一つの変数にまとめたAPIキーとトークンと、抽出したデータを入れた変数を利用し、update_statusでTwitterに投稿します。

api.update_status(tweet)
print(tweet)

©Copyright2022 FICH-LABO.All Rights Reserved.