Created
June 27, 2023 17:50
-
-
Save jaynetics/6f62e7fa79646c1c8a13e34ab76ba85c to your computer and use it in GitHub Desktop.
download all comments of a youtube video
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# usage: script.rb <video_id> <api_key> | |
require 'json' | |
require 'net/http' | |
video_id = ARGV[0].tap { |s| s&.length&.<(13) || fail('pass video id as first argument') } | |
key = ARGV[1].tap { |s| s&.length&.>(13) || fail('pass api key as second argument') } | |
url = "https://youtube.googleapis.com/youtube/v3/commentThreads?part=snippet&videoId=#{video_id}&key=#{key}" | |
items = [] | |
Net::HTTP.start(URI.parse(url).host, use_ssl: true) do |http| | |
loop do | |
puts "downloading comments page #{@next_page_token}" | |
response = http.get("#{url}#{@next_page_token && "&pageToken=#{@next_page_token}"}") | |
response.code.to_i == 200 || fail("#{response.code}: #{response.body}") | |
data = JSON(response.body) | |
items += data['items'] | |
break if data['items'].none? || (@next_page_token = data['nextPageToken']).to_s.empty? | |
end | |
end | |
File.write("#{video_id}_comments.json", items.to_json) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment