以下は、 Python YouTube APIを使用して要求したことを実現します。
from gdata.youtube import service
USERNAME = 'username@gmail.com'
PASSWORD = 'a_very_long_password'
VIDEO_ID = 'wf_IIbT8HGk'
def comments_generator(client, video_id):
comment_feed = client.GetYouTubeVideoCommentFeed(video_id=video_id)
while comment_feed is not None:
for comment in comment_feed.entry:
yield comment
next_link = comment_feed.GetNextLink()
if next_link is None:
comment_feed = None
else:
comment_feed = client.GetYouTubeVideoCommentFeed(next_link.href)
client = service.YouTubeService()
client.ClientLogin(USERNAME, PASSWORD)
for comment in comments_generator(client, VIDEO_ID):
author_name = comment.author[0].name.text
text = comment.content.text
print("{}: {}".format(author_name, text))
残念ながら、API は取得できるエントリの数を1000に制限しています。これは、手作りのGetYouTubeVideoCommentFeed
URL パラメーターを使用して微調整したバージョンを試したときに発生したエラーです。
gdata.service.RequestError: {'status': 400, 'body': 'You cannot request beyond item 1000.', 'reason': 'Bad Request'}
API の他のフィードでエントリを取得する場合も、同じ原則が適用されることに注意してください。
GetYouTubeVideoCommentFeed
URL パラメータを手作りする場合、その形式は次のとおりです。
'https://gdata.youtube.com/feeds/api/videos/{video_id}/comments?start-index={start_index}&max-results={max_results}'
次の制限が適用されます:start-index <= 1000
およびmax-results <= 50
.