2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RubyのみでTwitter Analyticsからimpressionを取得する

Last updated at Posted at 2017-11-13

#Rubyスクリプトで取得する
Twitter apiではimpressionやengagementは直接取得することができないため、Twitter Analyticsから別途取得する必要があったことから備忘録。ここでは直近の2つ目のツイートのデータをみることにする。

require 'capybara'
require 'capybara/dsl'
require 'capybara/poltergeist'
require 'phantomjs'

Capybara.configure do |config|
   config.run_server = false
   config.default_driver = :poltergeist
   config.app_host = 'https://twitter.com/login'
end

Capybara.register_driver :poltergeist do |app|
   Capybara::Poltergeist::Driver.new(app,:phantomjs => Phantomjs.path,:timout=>180,js_errors: false, phantomjs_options: ['--ignore-ssl-errors=yes'])
end

module Crawler
  class TwitterAnalytics
  include Capybara::DSL

  def get_data
  @accounts  = ["@hogehoge", "@hugahuga"]
  @passwords = ["foofoo", "barbar"]
  number     = 0
  @accounts.each do |account|
      visit('https://twitter.com/login')
      sleep(5)
      fill_in "session[username_or_email]", :with => account
      fill_in "session[password]", :with => @passwords[number]
      find(:xpath,'//*[@id="page-container"]/div/div[1]/form/div[2]/button').click
      account.slice!(0)
      visit('https://analytics.twitter.com/user/'+account+'/tweets')
      sleep(10)
      doc = Nokogiri::HTML.parse(page.html)
      impression = doc.xpath('//div[@class="tweet-activity-data impressions text-right col-md-1"]')
      engagement = doc.xpath('//div[@class="tweet-activity-data metric text-right col-md-2"]')
      puts "impression:" + impression.first(2).last.text
      puts "engagement:" + engagement.first(3).last.text
      Capybara.reset_session!
      number += 1
  end
 end
end
end
crawler = Crawler::TwitterAnalytics.new
crawler.get_data

##やっていること
要はスクレイピングです。
上記のpasswordとかを考慮すれば複数のアカウントに対応することができます。
Twitter Analyticsを有効化しておくことを忘れないようにしてください。

2
4
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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?