使用YouTube API搜索频道会返回不正确的结果

使用YouTube API搜索频道会返回不正确的结果,youtube,youtube-api,discord,discord.py,youtube-data-api,Youtube,Youtube Api,Discord,Discord.py,Youtube Data Api,使用这段代码,我可以搜索YouTube频道并返回它们的统计数据;然而,由于某些原因,只有大约一半的通道返回任何结果 例如,如果我使用这个,您可以看到我搜索了动物星球,但没有结果。然而,如果我们访问YouTube的网站并搜索相同的内容,我们会根据需要获得频道 为什么会发生这种情况?如何解决 这是我使用的代码: @commands.command() async def yt_test(self, ctx, *, search): api_key = '...'

使用这段代码,我可以搜索YouTube频道并返回它们的统计数据;然而,由于某些原因,只有大约一半的通道返回任何结果

例如,如果我使用这个,您可以看到我搜索了
动物星球
,但没有结果。然而,如果我们访问YouTube的网站并搜索相同的内容,我们会根据需要获得频道

为什么会发生这种情况?如何解决

这是我使用的代码:

    @commands.command()
    async def yt_test(self, ctx, *, search):
        api_key = '...'
        youtube = build('youtube', 'v3', developerKey=api_key)
        request = youtube.channels().list(
            part="snippet,statistics",
            forUsername=search,
            maxResults=1
        )
        response = request.execute()
        try:
            for item in response['items']:
                link = item['id']
                thumb_image = item['snippet']['thumbnails']['default']['url']
                views = "{:,}".format(int(item['statistics']['viewCount']))
                subs = "{:,}".format(int(item['statistics']['subscriberCount']))
                vidCount = "{:,}".format(int(item['statistics']['videoCount']))
        except:
            Notfound = discord.Embed(description= "Sorry, but this Channel was not located, check spelling" , color=0xfc0328)
            await ctx.send(embed=Notfound)
    
        finalresult = discord.Embed(title = search, url='https://www.youtube.com/channel/' + link, 
        description= '**Statistics**\nViews: ' + views + '\nSubscribers: ' + subs + "\nVideos: " + vidCount, color=0x00ff00)
        finalresult.set_thumbnail(url = thumb_image)
        await ctx.send(embed=finalresult)
        print(f"{ctx.author} looked up the profile of {search} --- in #{ctx.guild.name}")

您必须承认,通过向API端点传递参数来调用API端点与转到YouTube的Web UI以应用手动搜索绝不是一回事。为了让这些事情曝光,请容忍我一会儿

根据官方文档,使用
forUsername=…
调用的
Channels.list
端点会生成与频道相关的元数据,该频道的用户名作为参数
forUsername
的参数:

forUsername
(字符串)

forUsername
参数指定YouTube用户名,从而请求与该用户名关联的频道

根据2013-07-11,并非每个频道都必须附加用户名。因此,
Channels.list
endpoint完全可能不返回任何频道,如果
forUsername
的参数不代表YouTube用户名

如果您使用我的一个公共(麻省理工学院许可)Python 3脚本--,您将看到它不会为您查询的用户名
动物星球
返回任何内容:

$ python3 youtube-search.py --user-name "Animal Planet"
youtube-search.py: error: user name "Animal Planet": no associated channel found
但如果您按如下方式调用该脚本:

$ python3 youtube-search.py --search-term "Animal Planet" --type channel
UCkEBDbzLyH-LbB2FgMoSMaQ: Animal Planet
UCuTSm59-_kap6J7Se-orUVA: Animal Planet Latinoamérica
UCpvajaPSWvFlyl83xvzs65A: animalplanet românia
UCgyOEJZJLPKclqrDyUkZ6Ag: Animal planet 1
UCypzlOdJyyOR2NhKv0o3zig: 動物星球頻道/ Animal Planet Taiwan
UCmMm-p51c14XJ1p294faCmA: Animal Planet Brasil
UCejVe2sNPjjvfCXg35q_EQQ: Animal Planet Videos
UClQLf_zw2A_nRaB45HWTbtA: Your Animal Planet
UChQEdt9dBiCkcCch6LyrjtA: Cute Animal Planet
UCRIS8Y1kfrFvFF_6vt6_3Cg: Animal Planet Videos
当查询相同的搜索词并过滤
类型
频道
时,您将看到与YouTube的Web UI几乎相同的输出

请注意,您自己的结果(从youtube search.py获得的结果和youtube Web UI提供的另一个结果)很可能与上述结果不同;这是因为谷歌搜索是为发起查询的用户定制的

youtube search.py
和youtube Web UI获得的匹配结果集背后的解释如下:

与YouTube自己的搜索功能相对应的API端点可以通过其Web UI访问,这正是它的特点


请阅读youtube search.py的代码,让自己确信这一点:当使用
--搜索词“Animal Planet”--键入channel
调用它时,该脚本执行函数
服务。搜索词

班级服务:
...
定义搜索项(self,term,type=None):
resp=self.youtube.search().list(
q=术语,
类型=类型,
part='id,snippet',
字段='items(id,snippet(title))',
maxResults=self.max\u结果
).execute()
...

term
等于字符串
Animal Planet
type
等于字符串
channel
。因此,此脚本调用
Search.list
端点,将参数和前面提到的参数传递给它。

与您在示例
服务中所做的一样,返回频道id的代码是什么样子的。Search\u term
调用
Search.list
端点,并使用参数
字段='项(id,片段(标题))“
也是;因此,端点只返回频道ID和标题。请阅读下面的
服务实现。搜索\u term
以查看如何收集id。如果您要在代码中硬连线
type='channel'
,则items:
中的项的循环
将只执行
res.append(item['id']['channelId'])
,将
res初始化为
res=[]
在进入
for
循环之前。我的想法是让您的代码通过
动物星球
搜索示例返回频道id。然后我会把你提供的ID放到youtube API中,然后给我返回一个linkNote,
Search.list
很可能会返回几个频道ID(正如上面的
youtube Search.py
所做的那样)。仍然在试图弄清楚你写了什么,我对此一无所知,更不用说我没有问题;只需在我的答案下方发表评论。