3

我正在尝试检索特定用户集的订阅数和订阅者数。我正在使用适用于 Python 的 YouTube API。

我为订阅数量编写了以下代码。此代码从列表中逐一读取用户的 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()
4

1 回答 1

4

如果您只是想获取订阅者总数,则无需计算提要中的项目 - 它是数据 API v3 中提供的值。

您只需使用您正在查找的用户的 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 包含在响应中。

于 2013-02-19T07:54:02.840 回答