检索特定用户组的订阅和订阅者数量

时间:2013-02-18 15:10:26

标签: python youtube-api

我正在尝试检索特定用户组的订阅和订阅者数量。我正在使用YouTube API for Python。

我为订阅数量编写了以下代码。此代码逐个从列表中读取用户的ID,计算其订阅的数量,并将ID和数字写入CSV文件。但它不能正常工作。在少数第一个用户之后,它停止在文件中写入数字,并且无论如何数字都不正确。 我认为应该有比这个混乱更简单的东西。

谢谢,感谢您的建议和意见。

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()

1 个答案:

答案 0 :(得分:4)

如果您只是想获取订阅者总数,则无需计算Feed中的项目 - 它是Data API第3版中提供的值。

您只需要使用您正在查找的用户的channelId调用Channels资源: https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCDsO-0Yo5zpJk575nKXgMVA&key={YOUR_API_KEY}

响应:

{
 "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"
   }
  }
 ]
}

如您所见,subscriberCount包含在响应中。