【问题标题】:How to save results to file after every API call with ruby?每次使用 ruby​​ 调用 API 后如何将结果保存到文件中?
【发布时间】:2017-02-01 06:01:38
【问题描述】:

我使用这个简短的 ruby​​ 脚本来抓取 Twitter。问题是抓取大账户需要大量时间,而且因为我还在测试它,我看不出它是如何与大账户一起工作的。例如,我让它运行了一整天,它没有保存任何东西,所以我需要在每次 API 调用之后保存结果,而不仅仅是在整个脚本完成之后。感谢任何可以帮助我的人,或者至少为我指明正确的方向。这是代码:

def fetch_all_followers(twitter_username)
CSV.open("#{twitter_username}_friends_list.txt", 'w') do |csv|
@client.follower_ids(twitter_username).each_slice(5000).with_index do |slice, i|
  @client.users(slice).each_with_index do |f, j|
    csv << [i * 5000 + j + 1,f.screen_name]
    sleep 5
   end
  end
 end
end

fetch_all_followers("SOME_TWITTER_ACCOUNT")

【问题讨论】:

    标签: ruby api twitter


    【解决方案1】:

    经验法则:不要使用多余的第三者,这被称为“左垫综合症”。

    def fetch_all_followers(twitter_username)
      fname = "#{twitter_username}_friends_list.txt"
      @client.follower_ids(twitter_username)
             .each_slice(5000)
             .with_index do |slice, i|
        @client.users(slice)
               .each_with_index do |f, j|
                  File.open(fname, "a+") do |file|
                    file.write [i * 5000 + j + 1, f.screen_name, "\n"].join(',')
                  end
          sleep 5
        end
      end
    end
    
    fetch_all_followers("SOME_TWITTER_ACCOUNT")
    

    【讨论】:

    • 非常感谢
    猜你喜欢
    • 2017-04-19
    • 2020-02-15
    • 2020-10-12
    • 1970-01-01
    • 2011-03-21
    • 2013-12-18
    • 2019-04-04
    • 1970-01-01
    • 2020-12-28
    相关资源
    最近更新 更多