· 6 years ago · Nov 25, 2019, 04:14 PM
1import requests
2import json
3
4# API key for YouTube
5API_KEY = "AIzaSyDCx9U_U07tLvZZiw9Ys8KslUtyZz6jUus"
6# base URL
7URL = "https://www.googleapis.com/youtube/v3/commentThreads"
8# multiple parameters for the URL as a dictionary
9PARAMS = {
10 "key": API_KEY,
11 "textFormat": "plainText",
12 "part": "snippet,replies",
13 "order": "time",
14
15 "videoId": "",
16 "maxResults": 100,
17 "pageToken": "",
18}
19
20
21def fetch_comments(video_id):
22 """
23 Method for fetching the comments
24 of a specific video form YouTube
25 :video_id id of the YouTube video to fetch from
26 :return list of all comments of the video
27 """
28 p = PARAMS.copy()
29 p["videoId"] = video_id
30 # fetching the comments via HTTP GET with help from requests library
31 comments = [requests.get(url=URL, params=p).json()]
32
33 # loop for getting comments from different "comment pages"
34 while "nextPageToken" in comments[-1]:
35 p["pageToken"] = comments[-1]["nextPageToken"]
36 comments.append(requests.get(url=URL, params=p).json())
37
38 return [item for sublist in comments for item in sublist["items"]]
39
40
41# code that being run
42comments = fetch_comments("O6Ch-bvIUvI")
43print(comments)