import requests
import pprint
base_url = "https://www.googleapis.com/youtube/v3/"
api_function = "videos"
query = {
"key":"",
"chart":"mostPopular",
"maxResults":50,
"regionCode":"TW",
"part": "snippet,contentDetails,statistics",
}
response = requests.get(base_url + api_function, params=query)
if response.status_code == 200:
response_dict = response.json()
results1 = {
i+1: response_dict["items"][i]["snippet"]["channelTitle"]
for i in range(0,50)
}
results2 = {
i+1: response_dict["items"][i]["statistics"]["viewCount"]
for i in range(0,50)
}
results3 = {
i+1: response_dict["items"][i]["snippet"]["channelId"]
for i in range(0,50)
}
# pagination
if "nextPageToken" in response_dict.keys():
query['pageToken'] = response_dict["nextPageToken"]
response = requests.get(base_url + api_function, params = query)
if response.status_code == 200:
response_dict = response.json()
for i in range(0,50):
results1.update( {i+51: response_dict["items"][i]["snippet"]["channelTitle"] } )
if response.status_code == 200:
response_dict = response.json()
for i in range(0,50):
results2.update( {i+51: response_dict["items"][i]["statistics"]["viewCount"] } )
if response.status_code == 200:
response_dict = response.json()
for i in range(0,50):
results3.update( {i+51: response_dict["items"][i]["snippet"]["channelId"] } )
pprint.pprint(results1)
pprint.pprint(results2)
pprint.pprint(results3)
import requests
import pprint
base_url = "https://www.googleapis.com/youtube/v3/"
api_function = "channels"
query = {
"key":"",
"part": "snippet,statistics",
"id": "UCwWXGnvVmi-6Sfx2wf8S8tQ",
}
response = requests.get(base_url + api_function, params=query)
if response.status_code == 200:
response_dict = response.json()
results3_list = [ response_dict["items"][0]["statistics"]["subscriberCount"] ]
print(results3_list)
python課程學習中~
我正在著手yt前百大影片頻道的訂閱人數,
目前有找到前百大影片的頻道名稱和個別id,但不知道怎麼寫loop去替換"id",
進而從個別頻道找到訂閱數
QQ
感謝大家的提醒!!!
import requests
def getKey() -> str:
return 'YOUR KEY'
def queryYoutubeApi(baseUrl: str, function: str, queryParams: dict) -> requests.Response:
queryParams['key'] = getKey()
response = requests.get(baseUrl + function, params = queryParams)
return response
def queryYoutube_mostPopularVideo(numResults: int) -> list:
popularVideoSet = []
if numResults >= 1 and numResults <= 50:
queryParams = {
"chart": "mostPopular",
"maxResults": numResults,
"regionCode": "TW",
"part": "snippet,contentDetails,statistics"
}
response = queryYoutubeApi('https://www.googleapis.com/youtube/v3/', 'videos', queryParams)
if response.status_code == 200:
response = response.json()
for video in response['items']:
channelTitle = video['snippet']['channelTitle']
viewCount = int(video['statistics']['viewCount'])
channelId = video['snippet']['channelId']
popularVideoSet.append({
'channelTitle': channelTitle,
'viewCount': viewCount,
'channelId': channelId
})
return popularVideoSet
def queryYoutube_channelInfo(channelIds: list):
channelSet = []
channelIdStr = ''
for channelId in channelIds:
channelIdStr += ',' + str(channelId)
if not channelIdStr == '':
channelIdStr = channelIdStr[1:]
queryParams = {
"id": channelIdStr,
"part": "snippet,statistics"
}
response = queryYoutubeApi('https://www.googleapis.com/youtube/v3/', 'channels', queryParams)
if response.status_code == 200:
response = response.json()
for channel in response['items']:
id = channel['id']
title = channel['snippet']['title']
if channel['statistics']['hiddenSubscriberCount']:
subscriberCount = -1
else:
subscriberCount = int(channel['statistics']['subscriberCount'])
channelSet.append({
'id': id,
'title': title,
'subscriberCount': subscriberCount
})
return channelSet
""" main """
# Get popular videos.
popularVideoSet = queryYoutube_mostPopularVideo(50)
# Fetch channel ids.
channelIds = []
for video in popularVideoSet:
if not video['channelId'] in channelIds:
channelIds.append(video['channelId'])
# Get number of subscriber for each channel.
channelSet = queryYoutube_channelInfo(channelIds)
# print subcribers.
print('Total {} channels.\n'.format(len(channelSet)))
for channel in channelSet:
if channel['subscriberCount'] >= 0:
print('{} : {} subscriber(s)'.format(channel['title'], channel['subscriberCount']))
else:
print('{} : Hidden'.format(channel['title']))