【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サイトから取得してください
コンソール画面
コード解説
まず初めに下記ライブラリ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)
Yusuke
最新記事 by Yusuke (全て見る)
- 【準備は何が必要?】フリーランスクリエイターとは? - 2022年4月24日
- 【ファクタリング】フリーランスの為の先払いサービスとは? - 2022年4月23日
- 【初心者必見】フリーランスになる前に読んでおくべき本を紹介! - 2022年4月22日