Python+Tweepy
Twitterで検索し、そのユーザーのツイートにいいねして、フォローする
[code lang=”python”]
search_results = api.search(q="キーワード", count=1)
for result in search_results:
tweet_id = result.id #Tweetのidを取得
user_id = result.user._json[‘id’] #ユーザーのidを取得
try:
api.create_favorite(tweet_id) #ファボする
api.create_friendship(user_id) #フォローする
except Exception as e:
print(e)
[/code]
特定のユーザーの情報取得
[code lang=”python”]
user = api.get_user(‘@の後ろのスクリーンネーム’)
print(user.screen_name) #スクリーンネーム
print(user.id) #ユーザーID
print(user.name) #ユーザーネーム
print(user.followers_count) #フォロワー数
for friend in user.friends():
print(friend.screen_name)
[/code]
特定のユーザーのタイムラインを取得
[code lang=”python”]
tl = api.user_timeline(id=’@のうしろのスクリーンネーム’)
for a in tl:
tweet = str(a.author.name) + a.text
print(tweet)
[/code]
特定のキーワードで検索し、そのユーザーの情報やコメントを取得
[code lang=”python”]
word = "キーワード"
count = 3
results = api.search(q=word, count_count)
for result in results:
username = result.user._json[‘screen_name’]
user_id = result.id
print("ユーザーID:"+str(user_id))
user = result.user.name
print("ユーザー名:"+user)
tweet = result.text
print("ユーザーのコメント:"+tweet)
[/code]
特定ユーザーのコメントなどをCSVに書き込み
[code lang=”python”]
import tweepy
import csv
CONSUMER_KEY = ‘xxxxxxxxxxxxxxxx’
CONSUMER_SECRET = ‘xxxxxxxxxxxxxxxx’
ACCESS_TOKEN = ‘xxxxxxxxxxxxxxxx’
ACCESS_SECRET = ‘xxxxxxxxxxxxxxxx’
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
api = tweepy.API(auth)
tweet_data = []
for tweet in tweepy.Cursor(api.user_timeline,screen_name = "スクリーンネーム",exclude_replies = True).items(取得する数):
tweet_data.append([tweet.id,tweet.created_at,tweet.text.replace(‘\n’,”),tweet.favorite_count,tweet.retweet_count])
#csv出力
with open(‘test.csv’, ‘w’,newline=”,encoding=’utf-8′) as f:
writer = csv.writer(f, lineterminator=’\n’)
writer.writerow(["id","created_at","text","fav","RT"])
writer.writerows(tweet_data)
pass
[/code]
自分のタイムラインを10件取得
[code lang=”python”]
for tl in api.home_timeline(count=10):
print(tl.text)
[/code]
[code lang=”python”]
[/code]