Getting the number of subscribers and subscribers of a specific set of users

I am trying to get the number of subscribers and subscribers of a specific set of users. I am using YouTube API for Python.

I wrote the following code for the number of subscribers. This code reads the user IDs from the list one by one, counts their subscriptions and writes the ID and number to the CSV file. But it doesn't work as expected. after the first few users it stops writing numbers in the file, and the numbers are still not so correct. I think there must be something simpler than this mess.

Thank you, I appreciate your suggestions and comments.

import os
import gdata.youtube
import gdata.youtube.service
import time


def GetUserUrl (username):

    yt_service = gdata.youtube.service.YouTubeService()
    uri = 'https://gdata.youtube.com/feeds/api/users/%s/subscriptions?max-results=50&start-index=1' % username
    subscription_feed = yt_service.GetYouTubeSubscriptionFeed(uri)
    T1 = GetUserSub(subscription_feed)
    final = 0
    j = 1
    total = 0
    while j<800:
      j = j + 50
      sj = str(j)
      uri = 'https://gdata.youtube.com/feeds/api/users/%s/subscriptions?max-results=50&start-index=' % username+sj
      subscription_feed = yt_service.GetYouTubeSubscriptionFeed(uri)
      T2 = GetUserSub(subscription_feed)
      total = total + T2

    final = total + T1
    usersub.writelines([str(username),',',str(final),'\n'])

def GetUserSub (subscription_feed):

  i = 0
  for entry in subscription_feed.entry:
    i = i +1
  return i

usersub = open ('usersubscribtions.csv','w')
users=[]
userlist = open("user_ids_noduplicates1.txt","r")
text1 = userlist.readlines()

for l in text1:
        users.append(l.strip().split()[0])
x = 0
while (x<len(users)):

 try:
    GetUserUrl(users[x])
    time.sleep(0.4)
    x = x+1
 except:
    usersub.writelines([str(users[x]),'\n'])
    x = x+1
    pass

usersub.close()

      

+3


source to share


1 answer


If you're just trying to get the total number of subscribers, you don't need to count items in the feed - this is a preset value in v3 of the Data API.

You just need to make a call to the Channels resource using the channelId of the user you are looking for: https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCDsO-0Yo5zpJk575nKXgMVA&key= {YOUR_API_KEY}

Answer:



{
 "kind": "youtube#channelListResponse",
 "etag": "\"O7gZuruiUnq-GRpzm3HckV3Vx7o/wC5OTbvm5Z2-sKAqmTfH4YDQ-Gw\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "id": "UCDsO-0Yo5zpJk575nKXgMVA",
   "kind": "youtube#channel",
   "etag": "\"O7gZuruiUnq-GRpzm3HckV3Vx7o/xRjATA5YtH9wRO8Uq6Vq4D45vfQ\"",
   "statistics": {
    "viewCount": "80667849",
    "commentCount": "122605",
    "subscriberCount": "4716360",
    "videoCount": "163"
   }
  }
 ]
}

      

As you can see, the subscriber account is included in the response.

+3


source







All Articles