我正在尝试检索特定用户集的订阅数和订阅者数。我正在使用YouTube的Python 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()
如果您只是想获得订阅服务器的总数,则不需要计算提要中的项,这是Data API v3中提供的值。
您只需要使用要查找的用户的channelId调用Channels资源:https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCDsO-0Yo5zpJk575nKXgMVA&密钥={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包含在响应中。