获取特定用户集的订阅数量和订阅者数量
我正在尝试获取一组特定用户的订阅数量和订阅者数量。我使用的是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()
1 个回答
4
如果你只是想知道总共有多少个订阅者,其实不需要去数订阅源里的项目,因为在数据API的v3版本中,这个数字是直接提供的。
你只需要调用频道资源,使用你想查询的用户的频道ID就可以了: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"
}
}
]
}
你可以看到,返回的数据里包含了订阅者的数量。