LoginSignup
11
16

More than 5 years have passed since last update.

Python Twitter APIを使わずにツイートを収集

Last updated at Posted at 2019-02-09

Twitterアフィリエイトを行うにあたって

ツイートのパクリは欠かせません。ただし、Twitter APIを使ってツイートの収集をしていると、アカウントが凍結されてしまいます。
Twitter アカウント凍結
複数のアカウントを切り替えてTwitter APIをコールしていてもそのうちすべて凍結されます。
Twitter APIを使わずにツイートが収集できればこの問題は解決します。

ツイートにアクセス

こんな書式でアクセスすればJSONでツイートは得られます。
https://twitter.com/i/profiles/show/kabu01/timeline/tweets?include_available_features=1&include_entities=1&include_new_items_bar=true
解析が面倒。。。

twitter-scraperの利用

上記の形式でTwitter APIを使わずにツイートを収集できる twitter-scraper ライブラリを使います。 python 3.6 以上で利用できます。

$ pip install twitter-scraper

インストールしただけではエラーが出てしまいます。

File " path to /lib/python3.6/site-packages/twitter_scraper.py", line 42, in gen_tweets
replies = int(interactions[0].split(" ")[0].replace(comma, "").replace(dot,""))
ValueError: invalid literal for int() with base 10: '\n'

こんなエラーが出るので該当ファイルを次のように修正してください。
修正前

replies = int(interactions[0].split(" ")[0].replace(comma, "").replace(dot,""))
retweets = int(interactions[1].split(" ")[0].replace(comma, "").replace(dot,""))

修正後

try:
    replies = int(interactions[0].split(" ")[0].replace(comma, "").replace(dot, ""))
except ValueError:
    replies = 0

try:
    retweets = int(interactions[1].split(" ")[0].replace(comma, "").replace(dot, ""))
except ValueError:
    retweets = 0

ツイート収集

こんな風に使います。

from twitter_scraper import get_tweets
for tweet in get_tweets('kabu01', pages=1):
    print(tweet)
    print("\n")

こんな風にリンクや画像も含めて取得できます。


{'tweetId': '1087597341912125440', 'time': datetime.datetime(2019, 1, 22, 15, 26, 27), 
'text': '今日は長女の幼稚園で劇の発表会がありました。内容は何と「おおきなかぶ」(笑)\n劇のように今年は「大きな株」が抜けるでしょうか!?', 
'replies': 0, 'retweets': 0, 'likes': 10, 'entries': {'hashtags': [], 'urls': [], 'photos': [], 'videos': []}}


{'tweetId': '1085825146915479552', 'time': datetime.datetime(2019, 1, 17, 18, 4, 23), 
'text': '直近、こちらの2つの投資勉強会を申し込んだ。\n忘れないように記録しています。\nいつもYouTubeで坂本さんの動画を見ている。\nとても勉強になります。\n本人に会うことができて楽しみにしています。( ◠‿◠ )pic.twitter.com/0KamlaDJG3', 
'replies': 0, 'retweets': 0, 'likes': 4, 'entries': {'hashtags': [], 'urls': [], 
'photos': ['https://pbs.twimg.com/media/DxGgNYpVAAANxGu.jpg', 'https://pbs.twimg.com/media/DxGgNYnU0AATgfm.jpg'], 'videos': []}}


{'tweetId': '1087178896452141056', 'time': datetime.datetime(2019, 1, 21, 11, 43, 42), 
'text': '今月発売のDIME、2019年3月号「株で人生を変えた人に学ぶ勝ちワザ」に掲載されました。\n\n私は50ページに載りましたが、その他、著名な方も掲載されておりました。pic.twitter.com/C8TC7ADBeG', 
'replies': 0, 'retweets': 0, 'likes': 11, 'entries': {'hashtags': [], 'urls': [], 
'photos': ['https://pbs.twimg.com/media/DxZvcNHUYAEv3E9.jpg'], 'videos': []}}

11
16
0

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
11
16